liangsu9988 commited on
Commit
3e88ee7
1 Parent(s): 373f59d

Upload 505 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. diffusers/CITATION.cff +40 -0
  2. diffusers/CODE_OF_CONDUCT.md +129 -0
  3. diffusers/CONTRIBUTING.md +294 -0
  4. diffusers/LICENSE +201 -0
  5. diffusers/MANIFEST.in +2 -0
  6. diffusers/Makefile +96 -0
  7. diffusers/README.md +563 -0
  8. diffusers/_typos.toml +13 -0
  9. diffusers/docker/diffusers-flax-cpu/Dockerfile +44 -0
  10. diffusers/docker/diffusers-flax-tpu/Dockerfile +46 -0
  11. diffusers/docker/diffusers-onnxruntime-cpu/Dockerfile +44 -0
  12. diffusers/docker/diffusers-onnxruntime-cuda/Dockerfile +44 -0
  13. diffusers/docker/diffusers-pytorch-cpu/Dockerfile +43 -0
  14. diffusers/docker/diffusers-pytorch-cuda/Dockerfile +43 -0
  15. diffusers/docs/README.md +271 -0
  16. diffusers/docs/TRANSLATING.md +57 -0
  17. diffusers/docs/source/en/_toctree.yml +212 -0
  18. diffusers/docs/source/en/api/configuration.mdx +23 -0
  19. diffusers/docs/source/en/api/diffusion_pipeline.mdx +47 -0
  20. diffusers/docs/source/en/api/experimental/rl.mdx +15 -0
  21. diffusers/docs/source/en/api/loaders.mdx +30 -0
  22. diffusers/docs/source/en/api/logging.mdx +98 -0
  23. diffusers/docs/source/en/api/models.mdx +83 -0
  24. diffusers/docs/source/en/api/outputs.mdx +55 -0
  25. diffusers/docs/source/en/api/pipelines/alt_diffusion.mdx +83 -0
  26. diffusers/docs/source/en/api/pipelines/audio_diffusion.mdx +98 -0
  27. diffusers/docs/source/en/api/pipelines/cycle_diffusion.mdx +100 -0
  28. diffusers/docs/source/en/api/pipelines/dance_diffusion.mdx +34 -0
  29. diffusers/docs/source/en/api/pipelines/ddim.mdx +36 -0
  30. diffusers/docs/source/en/api/pipelines/ddpm.mdx +37 -0
  31. diffusers/docs/source/en/api/pipelines/dit.mdx +59 -0
  32. diffusers/docs/source/en/api/pipelines/latent_diffusion.mdx +49 -0
  33. diffusers/docs/source/en/api/pipelines/latent_diffusion_uncond.mdx +42 -0
  34. diffusers/docs/source/en/api/pipelines/overview.mdx +200 -0
  35. diffusers/docs/source/en/api/pipelines/paint_by_example.mdx +74 -0
  36. diffusers/docs/source/en/api/pipelines/pndm.mdx +35 -0
  37. diffusers/docs/source/en/api/pipelines/repaint.mdx +77 -0
  38. diffusers/docs/source/en/api/pipelines/score_sde_ve.mdx +36 -0
  39. diffusers/docs/source/en/api/pipelines/stable_diffusion/depth2img.mdx +33 -0
  40. diffusers/docs/source/en/api/pipelines/stable_diffusion/image_variation.mdx +31 -0
  41. diffusers/docs/source/en/api/pipelines/stable_diffusion/img2img.mdx +29 -0
  42. diffusers/docs/source/en/api/pipelines/stable_diffusion/inpaint.mdx +33 -0
  43. diffusers/docs/source/en/api/pipelines/stable_diffusion/latent_upscale.mdx +33 -0
  44. diffusers/docs/source/en/api/pipelines/stable_diffusion/overview.mdx +79 -0
  45. diffusers/docs/source/en/api/pipelines/stable_diffusion/pix2pix.mdx +70 -0
  46. diffusers/docs/source/en/api/pipelines/stable_diffusion/text2img.mdx +39 -0
  47. diffusers/docs/source/en/api/pipelines/stable_diffusion/upscale.mdx +32 -0
  48. diffusers/docs/source/en/api/pipelines/stable_diffusion_2.mdx +176 -0
  49. diffusers/docs/source/en/api/pipelines/stable_diffusion_safe.mdx +90 -0
  50. diffusers/docs/source/en/api/pipelines/stochastic_karras_ve.mdx +36 -0
diffusers/CITATION.cff ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ title: 'Diffusers: State-of-the-art diffusion models'
3
+ message: >-
4
+ If you use this software, please cite it using the
5
+ metadata from this file.
6
+ type: software
7
+ authors:
8
+ - given-names: Patrick
9
+ family-names: von Platen
10
+ - given-names: Suraj
11
+ family-names: Patil
12
+ - given-names: Anton
13
+ family-names: Lozhkov
14
+ - given-names: Pedro
15
+ family-names: Cuenca
16
+ - given-names: Nathan
17
+ family-names: Lambert
18
+ - given-names: Kashif
19
+ family-names: Rasul
20
+ - given-names: Mishig
21
+ family-names: Davaadorj
22
+ - given-names: Thomas
23
+ family-names: Wolf
24
+ repository-code: 'https://github.com/huggingface/diffusers'
25
+ abstract: >-
26
+ Diffusers provides pretrained diffusion models across
27
+ multiple modalities, such as vision and audio, and serves
28
+ as a modular toolbox for inference and training of
29
+ diffusion models.
30
+ keywords:
31
+ - deep-learning
32
+ - pytorch
33
+ - image-generation
34
+ - diffusion
35
+ - text2image
36
+ - image2image
37
+ - score-based-generative-modeling
38
+ - stable-diffusion
39
+ license: Apache-2.0
40
+ version: 0.12.1
diffusers/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, religion, or sexual identity
11
+ and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the
27
+ overall community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or
32
+ advances of any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email
36
+ address, without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ## Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ## Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ## Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ feedback@huggingface.co.
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ## Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ ### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ ### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series
87
+ of actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or
94
+ permanent ban.
95
+
96
+ ### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ ### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within
114
+ the community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.0, available at
120
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
121
+
122
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
123
+ enforcement ladder](https://github.com/mozilla/diversity).
124
+
125
+ [homepage]: https://www.contributor-covenant.org
126
+
127
+ For answers to common questions about this code of conduct, see the FAQ at
128
+ https://www.contributor-covenant.org/faq. Translations are available at
129
+ https://www.contributor-covenant.org/translations.
diffusers/CONTRIBUTING.md ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # How to contribute to diffusers?
18
+
19
+ Everyone is welcome to contribute, and we value everybody's contribution. Code
20
+ is thus not the only way to help the community. Answering questions, helping
21
+ others, reaching out and improving the documentations are immensely valuable to
22
+ the community.
23
+
24
+ It also helps us if you spread the word: reference the library from blog posts
25
+ on the awesome projects it made possible, shout out on Twitter every time it has
26
+ helped you, or simply star the repo to say "thank you".
27
+
28
+ Whichever way you choose to contribute, please be mindful to respect our
29
+ [code of conduct](https://github.com/huggingface/diffusers/blob/main/CODE_OF_CONDUCT.md).
30
+
31
+ ## You can contribute in so many ways!
32
+
33
+ There are 4 ways you can contribute to diffusers:
34
+ * Fixing outstanding issues with the existing code;
35
+ * Implementing [new diffusion pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines#contribution), [new schedulers](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers) or [new models](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models)
36
+ * [Contributing to the examples](https://github.com/huggingface/diffusers/tree/main/examples) or to the documentation;
37
+ * Submitting issues related to bugs or desired new features.
38
+
39
+ In particular there is a special [Good First Issue](https://github.com/huggingface/diffusers/contribute) listing.
40
+ It will give you a list of open Issues that are open to anybody to work on. Just comment in the issue that you'd like to work on it.
41
+ In that same listing you will also find some Issues with `Good Second Issue` label. These are
42
+ typically slightly more complicated than the Issues with just `Good First Issue` label. But if you
43
+ feel you know what you're doing, go for it.
44
+
45
+ *All are equally valuable to the community.*
46
+
47
+ ## Submitting a new issue or feature request
48
+
49
+ Do your best to follow these guidelines when submitting an issue or a feature
50
+ request. It will make it easier for us to come back to you quickly and with good
51
+ feedback.
52
+
53
+ ### Did you find a bug?
54
+
55
+ The 🧨 Diffusers library is robust and reliable thanks to the users who notify us of
56
+ the problems they encounter. So thank you for reporting an issue.
57
+
58
+ First, we would really appreciate it if you could **make sure the bug was not
59
+ already reported** (use the search bar on Github under Issues).
60
+
61
+ ### Do you want to implement a new diffusion pipeline / diffusion model?
62
+
63
+ Awesome! Please provide the following information:
64
+
65
+ * Short description of the diffusion pipeline and link to the paper;
66
+ * Link to the implementation if it is open-source;
67
+ * Link to the model weights if they are available.
68
+
69
+ If you are willing to contribute the model yourself, let us know so we can best
70
+ guide you.
71
+
72
+ ### Do you want a new feature (that is not a model)?
73
+
74
+ A world-class feature request addresses the following points:
75
+
76
+ 1. Motivation first:
77
+ * Is it related to a problem/frustration with the library? If so, please explain
78
+ why. Providing a code snippet that demonstrates the problem is best.
79
+ * Is it related to something you would need for a project? We'd love to hear
80
+ about it!
81
+ * Is it something you worked on and think could benefit the community?
82
+ Awesome! Tell us what problem it solved for you.
83
+ 2. Write a *full paragraph* describing the feature;
84
+ 3. Provide a **code snippet** that demonstrates its future use;
85
+ 4. In case this is related to a paper, please attach a link;
86
+ 5. Attach any additional information (drawings, screenshots, etc.) you think may help.
87
+
88
+ If your issue is well written we're already 80% of the way there by the time you
89
+ post it.
90
+
91
+ ## Start contributing! (Pull Requests)
92
+
93
+ Before writing code, we strongly advise you to search through the existing PRs or
94
+ issues to make sure that nobody is already working on the same thing. If you are
95
+ unsure, it is always a good idea to open an issue to get some feedback.
96
+
97
+ You will need basic `git` proficiency to be able to contribute to
98
+ 🧨 Diffusers. `git` is not the easiest tool to use but it has the greatest
99
+ manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
100
+ Git](https://git-scm.com/book/en/v2) is a very good reference.
101
+
102
+ Follow these steps to start contributing ([supported Python versions](https://github.com/huggingface/diffusers/blob/main/setup.py#L426)):
103
+
104
+ 1. Fork the [repository](https://github.com/huggingface/diffusers) by
105
+ clicking on the 'Fork' button on the repository's page. This creates a copy of the code
106
+ under your GitHub user account.
107
+
108
+ 2. Clone your fork to your local disk, and add the base repository as a remote:
109
+
110
+ ```bash
111
+ $ git clone git@github.com:<your Github handle>/diffusers.git
112
+ $ cd diffusers
113
+ $ git remote add upstream https://github.com/huggingface/diffusers.git
114
+ ```
115
+
116
+ 3. Create a new branch to hold your development changes:
117
+
118
+ ```bash
119
+ $ git checkout -b a-descriptive-name-for-my-changes
120
+ ```
121
+
122
+ **Do not** work on the `main` branch.
123
+
124
+ 4. Set up a development environment by running the following command in a virtual environment:
125
+
126
+ ```bash
127
+ $ pip install -e ".[dev]"
128
+ ```
129
+
130
+ (If diffusers was already installed in the virtual environment, remove
131
+ it with `pip uninstall diffusers` before reinstalling it in editable
132
+ mode with the `-e` flag.)
133
+
134
+ To run the full test suite, you might need the additional dependency on `transformers` and `datasets` which requires a separate source
135
+ install:
136
+
137
+ ```bash
138
+ $ git clone https://github.com/huggingface/transformers
139
+ $ cd transformers
140
+ $ pip install -e .
141
+ ```
142
+
143
+ ```bash
144
+ $ git clone https://github.com/huggingface/datasets
145
+ $ cd datasets
146
+ $ pip install -e .
147
+ ```
148
+
149
+ If you have already cloned that repo, you might need to `git pull` to get the most recent changes in the `datasets`
150
+ library.
151
+
152
+ 5. Develop the features on your branch.
153
+
154
+ As you work on the features, you should make sure that the test suite
155
+ passes. You should run the tests impacted by your changes like this:
156
+
157
+ ```bash
158
+ $ pytest tests/<TEST_TO_RUN>.py
159
+ ```
160
+
161
+ You can also run the full suite with the following command, but it takes
162
+ a beefy machine to produce a result in a decent amount of time now that
163
+ Diffusers has grown a lot. Here is the command for it:
164
+
165
+ ```bash
166
+ $ make test
167
+ ```
168
+
169
+ For more information about tests, check out the
170
+ [dedicated documentation](https://huggingface.co/docs/diffusers/testing)
171
+
172
+ 🧨 Diffusers relies on `black` and `isort` to format its source code
173
+ consistently. After you make changes, apply automatic style corrections and code verifications
174
+ that can't be automated in one go with:
175
+
176
+ ```bash
177
+ $ make style
178
+ ```
179
+
180
+ 🧨 Diffusers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality
181
+ control runs in CI, however you can also run the same checks with:
182
+
183
+ ```bash
184
+ $ make quality
185
+ ```
186
+
187
+ Once you're happy with your changes, add changed files using `git add` and
188
+ make a commit with `git commit` to record your changes locally:
189
+
190
+ ```bash
191
+ $ git add modified_file.py
192
+ $ git commit
193
+ ```
194
+
195
+ It is a good idea to sync your copy of the code with the original
196
+ repository regularly. This way you can quickly account for changes:
197
+
198
+ ```bash
199
+ $ git fetch upstream
200
+ $ git rebase upstream/main
201
+ ```
202
+
203
+ Push the changes to your account using:
204
+
205
+ ```bash
206
+ $ git push -u origin a-descriptive-name-for-my-changes
207
+ ```
208
+
209
+ 6. Once you are satisfied (**and the checklist below is happy too**), go to the
210
+ webpage of your fork on GitHub. Click on 'Pull request' to send your changes
211
+ to the project maintainers for review.
212
+
213
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors
214
+ too! So everyone can see the changes in the Pull request, work in your local
215
+ branch and push the changes to your fork. They will automatically appear in
216
+ the pull request.
217
+
218
+
219
+ ### Checklist
220
+
221
+ 1. The title of your pull request should be a summary of its contribution;
222
+ 2. If your pull request addresses an issue, please mention the issue number in
223
+ the pull request description to make sure they are linked (and people
224
+ consulting the issue know you are working on it);
225
+ 3. To indicate a work in progress please prefix the title with `[WIP]`. These
226
+ are useful to avoid duplicated work, and to differentiate it from PRs ready
227
+ to be merged;
228
+ 4. Make sure existing tests pass;
229
+ 5. Add high-coverage tests. No quality testing = no merge.
230
+ - If you are adding new `@slow` tests, make sure they pass using
231
+ `RUN_SLOW=1 python -m pytest tests/test_my_new_model.py`.
232
+ - If you are adding a new tokenizer, write tests, and make sure
233
+ `RUN_SLOW=1 python -m pytest tests/test_tokenization_{your_model_name}.py` passes.
234
+ CircleCI does not run the slow tests, but github actions does every night!
235
+ 6. All public methods must have informative docstrings that work nicely with sphinx. See `modeling_bert.py` for an
236
+ example.
237
+ 7. Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
238
+ the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference
239
+ them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
240
+ If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
241
+ to this dataset.
242
+
243
+ ### Tests
244
+
245
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
246
+ the [tests folder](https://github.com/huggingface/diffusers/tree/main/tests).
247
+
248
+ We like `pytest` and `pytest-xdist` because it's faster. From the root of the
249
+ repository, here's how to run tests with `pytest` for the library:
250
+
251
+ ```bash
252
+ $ python -m pytest -n auto --dist=loadfile -s -v ./tests/
253
+ ```
254
+
255
+ In fact, that's how `make test` is implemented (sans the `pip install` line)!
256
+
257
+ You can specify a smaller set of tests in order to test only the feature
258
+ you're working on.
259
+
260
+ By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to
261
+ `yes` to run them. This will download many gigabytes of models — make sure you
262
+ have enough disk space and a good Internet connection, or a lot of patience!
263
+
264
+ ```bash
265
+ $ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
266
+ ```
267
+
268
+ This means `unittest` is fully supported. Here's how to run tests with
269
+ `unittest`:
270
+
271
+ ```bash
272
+ $ python -m unittest discover -s tests -t . -v
273
+ $ python -m unittest discover -s examples -t examples -v
274
+ ```
275
+
276
+
277
+ ### Style guide
278
+
279
+ For documentation strings, 🧨 Diffusers follows the [google style](https://google.github.io/styleguide/pyguide.html).
280
+
281
+ **This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).**
282
+
283
+ ### Syncing forked main with upstream (HuggingFace) main
284
+
285
+ To avoid pinging the upstream repository which adds reference notes to each upstream PR and sends unnecessary notifications to the developers involved in these PRs,
286
+ when syncing the main branch of a forked repository, please, follow these steps:
287
+ 1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead merge directly into the forked main.
288
+ 2. If a PR is absolutely necessary, use the following steps after checking out your branch:
289
+ ```
290
+ $ git checkout -b your-branch-for-syncing
291
+ $ git pull --squash --no-commit upstream main
292
+ $ git commit -m '<your message without GitHub references>'
293
+ $ git push --set-upstream origin your-branch-for-syncing
294
+ ```
diffusers/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
diffusers/MANIFEST.in ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ include LICENSE
2
+ include src/diffusers/utils/model_card_template.md
diffusers/Makefile ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples
2
+
3
+ # make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
4
+ export PYTHONPATH = src
5
+
6
+ check_dirs := examples scripts src tests utils
7
+
8
+ modified_only_fixup:
9
+ $(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs)))
10
+ @if test -n "$(modified_py_files)"; then \
11
+ echo "Checking/fixing $(modified_py_files)"; \
12
+ black $(modified_py_files); \
13
+ ruff $(modified_py_files); \
14
+ else \
15
+ echo "No library .py files were modified"; \
16
+ fi
17
+
18
+ # Update src/diffusers/dependency_versions_table.py
19
+
20
+ deps_table_update:
21
+ @python setup.py deps_table_update
22
+
23
+ deps_table_check_updated:
24
+ @md5sum src/diffusers/dependency_versions_table.py > md5sum.saved
25
+ @python setup.py deps_table_update
26
+ @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1)
27
+ @rm md5sum.saved
28
+
29
+ # autogenerating code
30
+
31
+ autogenerate_code: deps_table_update
32
+
33
+ # Check that the repo is in a good state
34
+
35
+ repo-consistency:
36
+ python utils/check_dummies.py
37
+ python utils/check_repo.py
38
+ python utils/check_inits.py
39
+
40
+ # this target runs checks on all files
41
+
42
+ quality:
43
+ black --check $(check_dirs)
44
+ ruff $(check_dirs)
45
+ doc-builder style src/diffusers docs/source --max_len 119 --check_only --path_to_docs docs/source
46
+ python utils/check_doc_toc.py
47
+
48
+ # Format source code automatically and check is there are any problems left that need manual fixing
49
+
50
+ extra_style_checks:
51
+ python utils/custom_init_isort.py
52
+ doc-builder style src/diffusers docs/source --max_len 119 --path_to_docs docs/source
53
+ python utils/check_doc_toc.py --fix_and_overwrite
54
+
55
+ # this target runs checks on all files and potentially modifies some of them
56
+
57
+ style:
58
+ black $(check_dirs)
59
+ ruff $(check_dirs) --fix
60
+ ${MAKE} autogenerate_code
61
+ ${MAKE} extra_style_checks
62
+
63
+ # Super fast fix and check target that only works on relevant modified files since the branch was made
64
+
65
+ fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency
66
+
67
+ # Make marked copies of snippets of codes conform to the original
68
+
69
+ fix-copies:
70
+ python utils/check_copies.py --fix_and_overwrite
71
+ python utils/check_dummies.py --fix_and_overwrite
72
+
73
+ # Run tests for the library
74
+
75
+ test:
76
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/
77
+
78
+ # Run tests for examples
79
+
80
+ test-examples:
81
+ python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/
82
+
83
+
84
+ # Release stuff
85
+
86
+ pre-release:
87
+ python utils/release.py
88
+
89
+ pre-patch:
90
+ python utils/release.py --patch
91
+
92
+ post-release:
93
+ python utils/release.py --post_release
94
+
95
+ post-patch:
96
+ python utils/release.py --post_release --patch
diffusers/README.md ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <br>
3
+ <img src="./docs/source/en/imgs/diffusers_library.jpg" width="400"/>
4
+ <br>
5
+ <p>
6
+ <p align="center">
7
+ <a href="https://github.com/huggingface/diffusers/blob/main/LICENSE">
8
+ <img alt="GitHub" src="https://img.shields.io/github/license/huggingface/datasets.svg?color=blue">
9
+ </a>
10
+ <a href="https://github.com/huggingface/diffusers/releases">
11
+ <img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/diffusers.svg">
12
+ </a>
13
+ <a href="CODE_OF_CONDUCT.md">
14
+ <img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg">
15
+ </a>
16
+ </p>
17
+
18
+ 🤗 Diffusers provides pretrained diffusion models across multiple modalities, such as vision and audio, and serves
19
+ as a modular toolbox for inference and training of diffusion models.
20
+
21
+ More precisely, 🤗 Diffusers offers:
22
+
23
+ - State-of-the-art diffusion pipelines that can be run in inference with just a couple of lines of code (see [src/diffusers/pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines)). Check [this overview](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/README.md#pipelines-summary) to see all supported pipelines and their corresponding official papers.
24
+ - Various noise schedulers that can be used interchangeably for the preferred speed vs. quality trade-off in inference (see [src/diffusers/schedulers](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)).
25
+ - Multiple types of models, such as UNet, can be used as building blocks in an end-to-end diffusion system (see [src/diffusers/models](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models)).
26
+ - Training examples to show how to train the most popular diffusion model tasks (see [examples](https://github.com/huggingface/diffusers/tree/main/examples), *e.g.* [unconditional-image-generation](https://github.com/huggingface/diffusers/tree/main/examples/unconditional_image_generation)).
27
+
28
+ ## Installation
29
+
30
+ ### For PyTorch
31
+
32
+ **With `pip`** (official package)
33
+
34
+ ```bash
35
+ pip install --upgrade diffusers[torch]
36
+ ```
37
+
38
+ **With `conda`** (maintained by the community)
39
+
40
+ ```sh
41
+ conda install -c conda-forge diffusers
42
+ ```
43
+
44
+ ### For Flax
45
+
46
+ **With `pip`**
47
+
48
+ ```bash
49
+ pip install --upgrade diffusers[flax]
50
+ ```
51
+
52
+ **Apple Silicon (M1/M2) support**
53
+
54
+ Please, refer to [the documentation](https://huggingface.co/docs/diffusers/optimization/mps).
55
+
56
+ ## Contributing
57
+
58
+ We ❤️ contributions from the open-source community!
59
+ If you want to contribute to this library, please check out our [Contribution guide](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md).
60
+ You can look out for [issues](https://github.com/huggingface/diffusers/issues) you'd like to tackle to contribute to the library.
61
+ - See [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) for general opportunities to contribute
62
+ - See [New model/pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) to contribute exciting new diffusion models / diffusion pipelines
63
+ - See [New scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
64
+
65
+ Also, say 👋 in our public Discord channel <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>. We discuss the hottest trends about diffusion models, help each other with contributions, personal projects or
66
+ just hang out ☕.
67
+
68
+ ## Quickstart
69
+
70
+ In order to get started, we recommend taking a look at two notebooks:
71
+
72
+ - The [Getting started with Diffusers](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/diffusers_intro.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/diffusers_intro.ipynb) notebook, which showcases an end-to-end example of usage for diffusion models, schedulers and pipelines.
73
+ Take a look at this notebook to learn how to use the pipeline abstraction, which takes care of everything (model, scheduler, noise handling) for you, and also to understand each independent building block in the library.
74
+ - The [Training a diffusers model](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) notebook summarizes diffusion models training methods. This notebook takes a step-by-step approach to training your
75
+ diffusion models on an image dataset, with explanatory graphics.
76
+
77
+ ## Stable Diffusion is fully compatible with `diffusers`!
78
+
79
+ Stable Diffusion is a text-to-image latent diffusion model created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), [LAION](https://laion.ai/) and [RunwayML](https://runwayml.com/). It's trained on 512x512 images from a subset of the [LAION-5B](https://laion.ai/blog/laion-5b/) database. This model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts. With its 860M UNet and 123M text encoder, the model is relatively lightweight and runs on a GPU with at least 4GB VRAM.
80
+ See the [model card](https://huggingface.co/CompVis/stable-diffusion) for more information.
81
+
82
+
83
+ ### Text-to-Image generation with Stable Diffusion
84
+
85
+ First let's install
86
+
87
+ ```bash
88
+ pip install --upgrade diffusers transformers accelerate
89
+ ```
90
+
91
+ We recommend using the model in [half-precision (`fp16`)](https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/) as it gives almost always the same results as full
92
+ precision while being roughly twice as fast and requiring half the amount of GPU RAM.
93
+
94
+ ```python
95
+ import torch
96
+ from diffusers import StableDiffusionPipeline
97
+
98
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
99
+ pipe = pipe.to("cuda")
100
+
101
+ prompt = "a photo of an astronaut riding a horse on mars"
102
+ image = pipe(prompt).images[0]
103
+ ```
104
+
105
+ #### Running the model locally
106
+
107
+ You can also simply download the model folder and pass the path to the local folder to the `StableDiffusionPipeline`.
108
+
109
+ ```
110
+ git lfs install
111
+ git clone https://huggingface.co/runwayml/stable-diffusion-v1-5
112
+ ```
113
+
114
+ Assuming the folder is stored locally under `./stable-diffusion-v1-5`, you can run stable diffusion
115
+ as follows:
116
+
117
+ ```python
118
+ pipe = StableDiffusionPipeline.from_pretrained("./stable-diffusion-v1-5")
119
+ pipe = pipe.to("cuda")
120
+
121
+ prompt = "a photo of an astronaut riding a horse on mars"
122
+ image = pipe(prompt).images[0]
123
+ ```
124
+
125
+ If you are limited by GPU memory, you might want to consider chunking the attention computation in addition
126
+ to using `fp16`.
127
+ The following snippet should result in less than 4GB VRAM.
128
+
129
+ ```python
130
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
131
+ pipe = pipe.to("cuda")
132
+
133
+ prompt = "a photo of an astronaut riding a horse on mars"
134
+ pipe.enable_attention_slicing()
135
+ image = pipe(prompt).images[0]
136
+ ```
137
+
138
+ If you wish to use a different scheduler (e.g.: DDIM, LMS, PNDM/PLMS), you can instantiate
139
+ it before the pipeline and pass it to `from_pretrained`.
140
+
141
+ ```python
142
+ from diffusers import LMSDiscreteScheduler
143
+
144
+ pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
145
+
146
+ prompt = "a photo of an astronaut riding a horse on mars"
147
+ image = pipe(prompt).images[0]
148
+
149
+ image.save("astronaut_rides_horse.png")
150
+ ```
151
+
152
+ If you want to run Stable Diffusion on CPU or you want to have maximum precision on GPU,
153
+ please run the model in the default *full-precision* setting:
154
+
155
+ ```python
156
+ from diffusers import StableDiffusionPipeline
157
+
158
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
159
+
160
+ # disable the following line if you run on CPU
161
+ pipe = pipe.to("cuda")
162
+
163
+ prompt = "a photo of an astronaut riding a horse on mars"
164
+ image = pipe(prompt).images[0]
165
+
166
+ image.save("astronaut_rides_horse.png")
167
+ ```
168
+
169
+ ### JAX/Flax
170
+
171
+ Diffusers offers a JAX / Flax implementation of Stable Diffusion for very fast inference. JAX shines specially on TPU hardware because each TPU server has 8 accelerators working in parallel, but it runs great on GPUs too.
172
+
173
+ Running the pipeline with the default PNDMScheduler:
174
+
175
+ ```python
176
+ import jax
177
+ import numpy as np
178
+ from flax.jax_utils import replicate
179
+ from flax.training.common_utils import shard
180
+
181
+ from diffusers import FlaxStableDiffusionPipeline
182
+
183
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
184
+ "runwayml/stable-diffusion-v1-5", revision="flax", dtype=jax.numpy.bfloat16
185
+ )
186
+
187
+ prompt = "a photo of an astronaut riding a horse on mars"
188
+
189
+ prng_seed = jax.random.PRNGKey(0)
190
+ num_inference_steps = 50
191
+
192
+ num_samples = jax.device_count()
193
+ prompt = num_samples * [prompt]
194
+ prompt_ids = pipeline.prepare_inputs(prompt)
195
+
196
+ # shard inputs and rng
197
+ params = replicate(params)
198
+ prng_seed = jax.random.split(prng_seed, jax.device_count())
199
+ prompt_ids = shard(prompt_ids)
200
+
201
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
202
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
203
+ ```
204
+
205
+ **Note**:
206
+ If you are limited by TPU memory, please make sure to load the `FlaxStableDiffusionPipeline` in `bfloat16` precision instead of the default `float32` precision as done above. You can do so by telling diffusers to load the weights from "bf16" branch.
207
+
208
+ ```python
209
+ import jax
210
+ import numpy as np
211
+ from flax.jax_utils import replicate
212
+ from flax.training.common_utils import shard
213
+
214
+ from diffusers import FlaxStableDiffusionPipeline
215
+
216
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
217
+ "runwayml/stable-diffusion-v1-5", revision="bf16", dtype=jax.numpy.bfloat16
218
+ )
219
+
220
+ prompt = "a photo of an astronaut riding a horse on mars"
221
+
222
+ prng_seed = jax.random.PRNGKey(0)
223
+ num_inference_steps = 50
224
+
225
+ num_samples = jax.device_count()
226
+ prompt = num_samples * [prompt]
227
+ prompt_ids = pipeline.prepare_inputs(prompt)
228
+
229
+ # shard inputs and rng
230
+ params = replicate(params)
231
+ prng_seed = jax.random.split(prng_seed, jax.device_count())
232
+ prompt_ids = shard(prompt_ids)
233
+
234
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
235
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
236
+ ```
237
+
238
+ Diffusers also has a Image-to-Image generation pipeline with Flax/Jax
239
+ ```python
240
+ import jax
241
+ import numpy as np
242
+ import jax.numpy as jnp
243
+ from flax.jax_utils import replicate
244
+ from flax.training.common_utils import shard
245
+ import requests
246
+ from io import BytesIO
247
+ from PIL import Image
248
+ from diffusers import FlaxStableDiffusionImg2ImgPipeline
249
+
250
+ def create_key(seed=0):
251
+ return jax.random.PRNGKey(seed)
252
+ rng = create_key(0)
253
+
254
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
255
+ response = requests.get(url)
256
+ init_img = Image.open(BytesIO(response.content)).convert("RGB")
257
+ init_img = init_img.resize((768, 512))
258
+
259
+ prompts = "A fantasy landscape, trending on artstation"
260
+
261
+ pipeline, params = FlaxStableDiffusionImg2ImgPipeline.from_pretrained(
262
+ "CompVis/stable-diffusion-v1-4", revision="flax",
263
+ dtype=jnp.bfloat16,
264
+ )
265
+
266
+ num_samples = jax.device_count()
267
+ rng = jax.random.split(rng, jax.device_count())
268
+ prompt_ids, processed_image = pipeline.prepare_inputs(prompt=[prompts]*num_samples, image = [init_img]*num_samples)
269
+ p_params = replicate(params)
270
+ prompt_ids = shard(prompt_ids)
271
+ processed_image = shard(processed_image)
272
+
273
+ output = pipeline(
274
+ prompt_ids=prompt_ids,
275
+ image=processed_image,
276
+ params=p_params,
277
+ prng_seed=rng,
278
+ strength=0.75,
279
+ num_inference_steps=50,
280
+ jit=True,
281
+ height=512,
282
+ width=768).images
283
+
284
+ output_images = pipeline.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))
285
+ ```
286
+
287
+ Diffusers also has a Text-guided inpainting pipeline with Flax/Jax
288
+
289
+ ```python
290
+ import jax
291
+ import numpy as np
292
+ from flax.jax_utils import replicate
293
+ from flax.training.common_utils import shard
294
+ import PIL
295
+ import requests
296
+ from io import BytesIO
297
+
298
+
299
+ from diffusers import FlaxStableDiffusionInpaintPipeline
300
+
301
+ def download_image(url):
302
+ response = requests.get(url)
303
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
304
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
305
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
306
+
307
+ init_image = download_image(img_url).resize((512, 512))
308
+ mask_image = download_image(mask_url).resize((512, 512))
309
+
310
+ pipeline, params = FlaxStableDiffusionInpaintPipeline.from_pretrained("xvjiarui/stable-diffusion-2-inpainting")
311
+
312
+ prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
313
+ prng_seed = jax.random.PRNGKey(0)
314
+ num_inference_steps = 50
315
+
316
+ num_samples = jax.device_count()
317
+ prompt = num_samples * [prompt]
318
+ init_image = num_samples * [init_image]
319
+ mask_image = num_samples * [mask_image]
320
+ prompt_ids, processed_masked_images, processed_masks = pipeline.prepare_inputs(prompt, init_image, mask_image)
321
+
322
+
323
+ # shard inputs and rng
324
+ params = replicate(params)
325
+ prng_seed = jax.random.split(prng_seed, jax.device_count())
326
+ prompt_ids = shard(prompt_ids)
327
+ processed_masked_images = shard(processed_masked_images)
328
+ processed_masks = shard(processed_masks)
329
+
330
+ images = pipeline(prompt_ids, processed_masks, processed_masked_images, params, prng_seed, num_inference_steps, jit=True).images
331
+ images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
332
+ ```
333
+
334
+ ### Image-to-Image text-guided generation with Stable Diffusion
335
+
336
+ The `StableDiffusionImg2ImgPipeline` lets you pass a text prompt and an initial image to condition the generation of new images.
337
+
338
+ ```python
339
+ import requests
340
+ import torch
341
+ from PIL import Image
342
+ from io import BytesIO
343
+
344
+ from diffusers import StableDiffusionImg2ImgPipeline
345
+
346
+ # load the pipeline
347
+ device = "cuda"
348
+ model_id_or_path = "runwayml/stable-diffusion-v1-5"
349
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
350
+
351
+ # or download via git clone https://huggingface.co/runwayml/stable-diffusion-v1-5
352
+ # and pass `model_id_or_path="./stable-diffusion-v1-5"`.
353
+ pipe = pipe.to(device)
354
+
355
+ # let's download an initial image
356
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
357
+
358
+ response = requests.get(url)
359
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
360
+ init_image = init_image.resize((768, 512))
361
+
362
+ prompt = "A fantasy landscape, trending on artstation"
363
+
364
+ images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
365
+
366
+ images[0].save("fantasy_landscape.png")
367
+ ```
368
+ You can also run this example on colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb)
369
+
370
+ ### In-painting using Stable Diffusion
371
+
372
+ The `StableDiffusionInpaintPipeline` lets you edit specific parts of an image by providing a mask and a text prompt.
373
+
374
+ ```python
375
+ import PIL
376
+ import requests
377
+ import torch
378
+ from io import BytesIO
379
+
380
+ from diffusers import StableDiffusionInpaintPipeline
381
+
382
+ def download_image(url):
383
+ response = requests.get(url)
384
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
385
+
386
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
387
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
388
+
389
+ init_image = download_image(img_url).resize((512, 512))
390
+ mask_image = download_image(mask_url).resize((512, 512))
391
+
392
+ pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16)
393
+ pipe = pipe.to("cuda")
394
+
395
+ prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
396
+ image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
397
+ ```
398
+
399
+ ### Tweak prompts reusing seeds and latents
400
+
401
+ You can generate your own latents to reproduce results, or tweak your prompt on a specific result you liked.
402
+ Please have a look at [Reusing seeds for deterministic generation](https://huggingface.co/docs/diffusers/main/en/using-diffusers/reusing_seeds).
403
+
404
+ ## Fine-Tuning Stable Diffusion
405
+
406
+ Fine-tuning techniques make it possible to adapt Stable Diffusion to your own dataset, or add new subjects to it. These are some of the techniques supported in `diffusers`:
407
+
408
+ Textual Inversion is a technique for capturing novel concepts from a small number of example images in a way that can later be used to control text-to-image pipelines. It does so by learning new 'words' in the embedding space of the pipeline's text encoder. These special words can then be used within text prompts to achieve very fine-grained control of the resulting images.
409
+
410
+ - Textual Inversion. Capture novel concepts from a small set of sample images, and associate them with new "words" in the embedding space of the text encoder. Please, refer to [our training examples](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion) or [documentation](https://huggingface.co/docs/diffusers/training/text_inversion) to try for yourself.
411
+
412
+ - Dreambooth. Another technique to capture new concepts in Stable Diffusion. This method fine-tunes the UNet (and, optionally, also the text encoder) of the pipeline to achieve impressive results. Please, refer to [our training example](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth) and [training report](https://huggingface.co/blog/dreambooth) for additional details and training recommendations.
413
+
414
+ - Full Stable Diffusion fine-tuning. If you have a more sizable dataset with a specific look or style, you can fine-tune Stable Diffusion so that it outputs images following those examples. This was the approach taken to create [a Pokémon Stable Diffusion model](https://huggingface.co/justinpinkney/pokemon-stable-diffusion) (by Justing Pinkney / Lambda Labs), [a Japanese specific version of Stable Diffusion](https://huggingface.co/spaces/rinna/japanese-stable-diffusion) (by [Rinna Co.](https://github.com/rinnakk/japanese-stable-diffusion/) and others. You can start at [our text-to-image fine-tuning example](https://github.com/huggingface/diffusers/tree/main/examples/text_to_image) and go from there.
415
+
416
+
417
+ ## Stable Diffusion Community Pipelines
418
+
419
+ The release of Stable Diffusion as an open source model has fostered a lot of interesting ideas and experimentation.
420
+ Our [Community Examples folder](https://github.com/huggingface/diffusers/tree/main/examples/community) contains many ideas worth exploring, like interpolating to create animated videos, using CLIP Guidance for additional prompt fidelity, term weighting, and much more! [Take a look](https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview) and [contribute your own](https://huggingface.co/docs/diffusers/using-diffusers/contribute_pipeline).
421
+
422
+ ## Other Examples
423
+
424
+ There are many ways to try running Diffusers! Here we outline code-focused tools (primarily using `DiffusionPipeline`s and Google Colab) and interactive web-tools.
425
+
426
+ ### Running Code
427
+
428
+ If you want to run the code yourself 💻, you can try out:
429
+ - [Text-to-Image Latent Diffusion](https://huggingface.co/CompVis/ldm-text2im-large-256)
430
+ ```python
431
+ # !pip install diffusers["torch"] transformers
432
+ from diffusers import DiffusionPipeline
433
+
434
+ device = "cuda"
435
+ model_id = "CompVis/ldm-text2im-large-256"
436
+
437
+ # load model and scheduler
438
+ ldm = DiffusionPipeline.from_pretrained(model_id)
439
+ ldm = ldm.to(device)
440
+
441
+ # run pipeline in inference (sample random noise and denoise)
442
+ prompt = "A painting of a squirrel eating a burger"
443
+ image = ldm([prompt], num_inference_steps=50, eta=0.3, guidance_scale=6).images[0]
444
+
445
+ # save image
446
+ image.save("squirrel.png")
447
+ ```
448
+ - [Unconditional Diffusion with discrete scheduler](https://huggingface.co/google/ddpm-celebahq-256)
449
+ ```python
450
+ # !pip install diffusers["torch"]
451
+ from diffusers import DDPMPipeline, DDIMPipeline, PNDMPipeline
452
+
453
+ model_id = "google/ddpm-celebahq-256"
454
+ device = "cuda"
455
+
456
+ # load model and scheduler
457
+ ddpm = DDPMPipeline.from_pretrained(model_id) # you can replace DDPMPipeline with DDIMPipeline or PNDMPipeline for faster inference
458
+ ddpm.to(device)
459
+
460
+ # run pipeline in inference (sample random noise and denoise)
461
+ image = ddpm().images[0]
462
+
463
+ # save image
464
+ image.save("ddpm_generated_image.png")
465
+ ```
466
+ - [Unconditional Latent Diffusion](https://huggingface.co/CompVis/ldm-celebahq-256)
467
+ - [Unconditional Diffusion with continuous scheduler](https://huggingface.co/google/ncsnpp-ffhq-1024)
468
+
469
+ **Other Image Notebooks**:
470
+ * [image-to-image generation with Stable Diffusion](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb) ![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg),
471
+ * [tweak images via repeated Stable Diffusion seeds](https://colab.research.google.com/github/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb) ![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg),
472
+
473
+ **Diffusers for Other Modalities**:
474
+ * [Molecule conformation generation](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/geodiff_molecule_conformation.ipynb) ![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg),
475
+ * [Model-based reinforcement learning](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/reinforcement_learning_with_diffusers.ipynb) ![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg),
476
+
477
+ ### Web Demos
478
+ If you just want to play around with some web demos, you can try out the following 🚀 Spaces:
479
+ | Model | Hugging Face Spaces |
480
+ |-------------------------------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
481
+ | Text-to-Image Latent Diffusion | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/CompVis/text2img-latent-diffusion) |
482
+ | Faces generator | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/CompVis/celeba-latent-diffusion) |
483
+ | DDPM with different schedulers | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/fusing/celeba-diffusion) |
484
+ | Conditional generation from sketch | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/huggingface/diffuse-the-rest) |
485
+ | Composable diffusion | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/Shuang59/Composable-Diffusion) |
486
+
487
+ ## Definitions
488
+
489
+ **Models**: Neural network that models $p_\theta(\mathbf{x}_{t-1}|\mathbf{x}_t)$ (see image below) and is trained end-to-end to *denoise* a noisy input to an image.
490
+ *Examples*: UNet, Conditioned UNet, 3D UNet, Transformer UNet
491
+
492
+ <p align="center">
493
+ <img src="https://user-images.githubusercontent.com/10695622/174349667-04e9e485-793b-429a-affe-096e8199ad5b.png" width="800"/>
494
+ <br>
495
+ <em> Figure from DDPM paper (https://arxiv.org/abs/2006.11239). </em>
496
+ <p>
497
+
498
+ **Schedulers**: Algorithm class for both **inference** and **training**.
499
+ The class provides functionality to compute previous image according to alpha, beta schedule as well as predict noise for training. Also known as **Samplers**.
500
+ *Examples*: [DDPM](https://arxiv.org/abs/2006.11239), [DDIM](https://arxiv.org/abs/2010.02502), [PNDM](https://arxiv.org/abs/2202.09778), [DEIS](https://arxiv.org/abs/2204.13902)
501
+
502
+ <p align="center">
503
+ <img src="https://user-images.githubusercontent.com/10695622/174349706-53d58acc-a4d1-4cda-b3e8-432d9dc7ad38.png" width="800"/>
504
+ <br>
505
+ <em> Sampling and training algorithms. Figure from DDPM paper (https://arxiv.org/abs/2006.11239). </em>
506
+ <p>
507
+
508
+
509
+ **Diffusion Pipeline**: End-to-end pipeline that includes multiple diffusion models, possible text encoders, ...
510
+ *Examples*: Glide, Latent-Diffusion, Imagen, DALL-E 2
511
+
512
+ <p align="center">
513
+ <img src="https://user-images.githubusercontent.com/10695622/174348898-481bd7c2-5457-4830-89bc-f0907756f64c.jpeg" width="550"/>
514
+ <br>
515
+ <em> Figure from ImageGen (https://imagen.research.google/). </em>
516
+ <p>
517
+
518
+ ## Philosophy
519
+
520
+ - Readability and clarity is preferred over highly optimized code. A strong importance is put on providing readable, intuitive and elementary code design. *E.g.*, the provided [schedulers](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers) are separated from the provided [models](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models) and provide well-commented code that can be read alongside the original paper.
521
+ - Diffusers is **modality independent** and focuses on providing pretrained models and tools to build systems that generate **continuous outputs**, *e.g.* vision and audio.
522
+ - Diffusion models and schedulers are provided as concise, elementary building blocks. In contrast, diffusion pipelines are a collection of end-to-end diffusion systems that can be used out-of-the-box, should stay as close as possible to their original implementation and can include components of another library, such as text-encoders. Examples for diffusion pipelines are [Glide](https://github.com/openai/glide-text2im) and [Latent Diffusion](https://github.com/CompVis/latent-diffusion).
523
+
524
+ ## In the works
525
+
526
+ For the first release, 🤗 Diffusers focuses on text-to-image diffusion techniques. However, diffusers can be used for much more than that! Over the upcoming releases, we'll be focusing on:
527
+
528
+ - Diffusers for audio
529
+ - Diffusers for reinforcement learning (initial work happening in https://github.com/huggingface/diffusers/pull/105).
530
+ - Diffusers for video generation
531
+ - Diffusers for molecule generation (initial work happening in https://github.com/huggingface/diffusers/pull/54)
532
+
533
+ A few pipeline components are already being worked on, namely:
534
+
535
+ - BDDMPipeline for spectrogram-to-sound vocoding
536
+ - GLIDEPipeline to support OpenAI's GLIDE model
537
+ - Grad-TTS for text to audio generation / conditional audio generation
538
+
539
+ We want diffusers to be a toolbox useful for diffusers models in general; if you find yourself limited in any way by the current API, or would like to see additional models, schedulers, or techniques, please open a [GitHub issue](https://github.com/huggingface/diffusers/issues) mentioning what you would like to see.
540
+
541
+ ## Credits
542
+
543
+ This library concretizes previous work by many different authors and would not have been possible without their great research and implementations. We'd like to thank, in particular, the following implementations which have helped us in our development and without which the API could not have been as polished today:
544
+
545
+ - @CompVis' latent diffusion models library, available [here](https://github.com/CompVis/latent-diffusion)
546
+ - @hojonathanho original DDPM implementation, available [here](https://github.com/hojonathanho/diffusion) as well as the extremely useful translation into PyTorch by @pesser, available [here](https://github.com/pesser/pytorch_diffusion)
547
+ - @ermongroup's DDIM implementation, available [here](https://github.com/ermongroup/ddim).
548
+ - @yang-song's Score-VE and Score-VP implementations, available [here](https://github.com/yang-song/score_sde_pytorch)
549
+
550
+ We also want to thank @heejkoo for the very helpful overview of papers, code and resources on diffusion models, available [here](https://github.com/heejkoo/Awesome-Diffusion-Models) as well as @crowsonkb and @rromb for useful discussions and insights.
551
+
552
+ ## Citation
553
+
554
+ ```bibtex
555
+ @misc{von-platen-etal-2022-diffusers,
556
+ author = {Patrick von Platen and Suraj Patil and Anton Lozhkov and Pedro Cuenca and Nathan Lambert and Kashif Rasul and Mishig Davaadorj and Thomas Wolf},
557
+ title = {Diffusers: State-of-the-art diffusion models},
558
+ year = {2022},
559
+ publisher = {GitHub},
560
+ journal = {GitHub repository},
561
+ howpublished = {\url{https://github.com/huggingface/diffusers}}
562
+ }
563
+ ```
diffusers/_typos.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Files for typos
2
+ # Instruction: https://github.com/marketplace/actions/typos-action#getting-started
3
+
4
+ [default.extend-identifiers]
5
+
6
+ [default.extend-words]
7
+ NIN="NIN" # NIN is used in scripts/convert_ncsnpp_original_checkpoint_to_diffusers.py
8
+ nd="np" # nd may be np (numpy)
9
+ parms="parms" # parms is used in scripts/convert_original_stable_diffusion_to_diffusers.py
10
+
11
+
12
+ [files]
13
+ extend-exclude = ["_typos.toml"]
diffusers/docker/diffusers-flax-cpu/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ # follow the instructions here: https://cloud.google.com/tpu/docs/run-in-container#train_a_jax_model_in_a_docker_container
26
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
27
+ python3 -m pip install --upgrade --no-cache-dir \
28
+ clu \
29
+ "jax[cpu]>=0.2.16,!=0.3.2" \
30
+ "flax>=0.4.1" \
31
+ "jaxlib>=0.1.65" && \
32
+ python3 -m pip install --no-cache-dir \
33
+ accelerate \
34
+ datasets \
35
+ hf-doc-builder \
36
+ huggingface-hub \
37
+ Jinja2 \
38
+ librosa \
39
+ numpy \
40
+ scipy \
41
+ tensorboard \
42
+ transformers
43
+
44
+ CMD ["/bin/bash"]
diffusers/docker/diffusers-flax-tpu/Dockerfile ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ # follow the instructions here: https://cloud.google.com/tpu/docs/run-in-container#train_a_jax_model_in_a_docker_container
26
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
27
+ python3 -m pip install --no-cache-dir \
28
+ "jax[tpu]>=0.2.16,!=0.3.2" \
29
+ -f https://storage.googleapis.com/jax-releases/libtpu_releases.html && \
30
+ python3 -m pip install --upgrade --no-cache-dir \
31
+ clu \
32
+ "flax>=0.4.1" \
33
+ "jaxlib>=0.1.65" && \
34
+ python3 -m pip install --no-cache-dir \
35
+ accelerate \
36
+ datasets \
37
+ hf-doc-builder \
38
+ huggingface-hub \
39
+ Jinja2 \
40
+ librosa \
41
+ numpy \
42
+ scipy \
43
+ tensorboard \
44
+ transformers
45
+
46
+ CMD ["/bin/bash"]
diffusers/docker/diffusers-onnxruntime-cpu/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
26
+ python3 -m pip install --no-cache-dir \
27
+ torch \
28
+ torchvision \
29
+ torchaudio \
30
+ onnxruntime \
31
+ --extra-index-url https://download.pytorch.org/whl/cpu && \
32
+ python3 -m pip install --no-cache-dir \
33
+ accelerate \
34
+ datasets \
35
+ hf-doc-builder \
36
+ huggingface-hub \
37
+ Jinja2 \
38
+ librosa \
39
+ numpy \
40
+ scipy \
41
+ tensorboard \
42
+ transformers
43
+
44
+ CMD ["/bin/bash"]
diffusers/docker/diffusers-onnxruntime-cuda/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
26
+ python3 -m pip install --no-cache-dir \
27
+ torch \
28
+ torchvision \
29
+ torchaudio \
30
+ "onnxruntime-gpu>=1.13.1" \
31
+ --extra-index-url https://download.pytorch.org/whl/cu117 && \
32
+ python3 -m pip install --no-cache-dir \
33
+ accelerate \
34
+ datasets \
35
+ hf-doc-builder \
36
+ huggingface-hub \
37
+ Jinja2 \
38
+ librosa \
39
+ numpy \
40
+ scipy \
41
+ tensorboard \
42
+ transformers
43
+
44
+ CMD ["/bin/bash"]
diffusers/docker/diffusers-pytorch-cpu/Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
26
+ python3 -m pip install --no-cache-dir \
27
+ torch \
28
+ torchvision \
29
+ torchaudio \
30
+ --extra-index-url https://download.pytorch.org/whl/cpu && \
31
+ python3 -m pip install --no-cache-dir \
32
+ accelerate \
33
+ datasets \
34
+ hf-doc-builder \
35
+ huggingface-hub \
36
+ Jinja2 \
37
+ librosa \
38
+ numpy \
39
+ scipy \
40
+ tensorboard \
41
+ transformers
42
+
43
+ CMD ["/bin/bash"]
diffusers/docker/diffusers-pytorch-cuda/Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.7.1-cudnn8-runtime-ubuntu20.04
2
+ LABEL maintainer="Hugging Face"
3
+ LABEL repository="diffusers"
4
+
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ RUN apt update && \
8
+ apt install -y bash \
9
+ build-essential \
10
+ git \
11
+ git-lfs \
12
+ curl \
13
+ ca-certificates \
14
+ libsndfile1-dev \
15
+ python3.8 \
16
+ python3-pip \
17
+ python3.8-venv && \
18
+ rm -rf /var/lib/apt/lists
19
+
20
+ # make sure to use venv
21
+ RUN python3 -m venv /opt/venv
22
+ ENV PATH="/opt/venv/bin:$PATH"
23
+
24
+ # pre-install the heavy dependencies (these can later be overridden by the deps from setup.py)
25
+ RUN python3 -m pip install --no-cache-dir --upgrade pip && \
26
+ python3 -m pip install --no-cache-dir \
27
+ torch \
28
+ torchvision \
29
+ torchaudio \
30
+ --extra-index-url https://download.pytorch.org/whl/cu117 && \
31
+ python3 -m pip install --no-cache-dir \
32
+ accelerate \
33
+ datasets \
34
+ hf-doc-builder \
35
+ huggingface-hub \
36
+ Jinja2 \
37
+ librosa \
38
+ numpy \
39
+ scipy \
40
+ tensorboard \
41
+ transformers
42
+
43
+ CMD ["/bin/bash"]
diffusers/docs/README.md ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022- The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Generating the documentation
18
+
19
+ To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
20
+ you can install them with the following command, at the root of the code repository:
21
+
22
+ ```bash
23
+ pip install -e ".[docs]"
24
+ ```
25
+
26
+ Then you need to install our open source documentation builder tool:
27
+
28
+ ```bash
29
+ pip install git+https://github.com/huggingface/doc-builder
30
+ ```
31
+
32
+ ---
33
+ **NOTE**
34
+
35
+ You only need to generate the documentation to inspect it locally (if you're planning changes and want to
36
+ check how they look before committing for instance). You don't have to commit the built documentation.
37
+
38
+ ---
39
+
40
+ ## Previewing the documentation
41
+
42
+ To preview the docs, first install the `watchdog` module with:
43
+
44
+ ```bash
45
+ pip install watchdog
46
+ ```
47
+
48
+ Then run the following command:
49
+
50
+ ```bash
51
+ doc-builder preview {package_name} {path_to_docs}
52
+ ```
53
+
54
+ For example:
55
+
56
+ ```bash
57
+ doc-builder preview diffusers docs/source/en
58
+ ```
59
+
60
+ The docs will be viewable at [http://localhost:3000](http://localhost:3000). You can also preview the docs once you have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives.
61
+
62
+ ---
63
+ **NOTE**
64
+
65
+ The `preview` command only works with existing doc files. When you add a completely new file, you need to update `_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again).
66
+
67
+ ---
68
+
69
+ ## Adding a new element to the navigation bar
70
+
71
+ Accepted files are Markdown (.md or .mdx).
72
+
73
+ Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting
74
+ the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/diffusers/blob/main/docs/source/_toctree.yml) file.
75
+
76
+ ## Renaming section headers and moving sections
77
+
78
+ It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.
79
+
80
+ Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor.
81
+
82
+ So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file:
83
+
84
+ ```
85
+ Sections that were moved:
86
+
87
+ [ <a href="#section-b">Section A</a><a id="section-a"></a> ]
88
+ ```
89
+ and of course, if you moved it to another file, then:
90
+
91
+ ```
92
+ Sections that were moved:
93
+
94
+ [ <a href="../new-file#section-b">Section A</a><a id="section-a"></a> ]
95
+ ```
96
+
97
+ Use the relative style to link to the new file so that the versioned docs continue to work.
98
+
99
+ For an example of a rich moved section set please see the very end of [the transformers Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.mdx).
100
+
101
+
102
+ ## Writing Documentation - Specification
103
+
104
+ The `huggingface/diffusers` documentation follows the
105
+ [Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings,
106
+ although we can write them directly in Markdown.
107
+
108
+ ### Adding a new tutorial
109
+
110
+ Adding a new tutorial or section is done in two steps:
111
+
112
+ - Add a new file under `docs/source`. This file can either be ReStructuredText (.rst) or Markdown (.md).
113
+ - Link that file in `docs/source/_toctree.yml` on the correct toc-tree.
114
+
115
+ Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so
116
+ depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or four.
117
+
118
+ ### Adding a new pipeline/scheduler
119
+
120
+ When adding a new pipeline:
121
+
122
+ - create a file `xxx.mdx` under `docs/source/api/pipelines` (don't hesitate to copy an existing file as template).
123
+ - Link that file in (*Diffusers Summary*) section in `docs/source/api/pipelines/overview.mdx`, along with the link to the paper, and a colab notebook (if available).
124
+ - Write a short overview of the diffusion model:
125
+ - Overview with paper & authors
126
+ - Paper abstract
127
+ - Tips and tricks and how to use it best
128
+ - Possible an end-to-end example of how to use it
129
+ - Add all the pipeline classes that should be linked in the diffusion model. These classes should be added using our Markdown syntax. By default as follows:
130
+
131
+ ```
132
+ ## XXXPipeline
133
+
134
+ [[autodoc]] XXXPipeline
135
+ - all
136
+ - __call__
137
+ ```
138
+
139
+ This will include every public method of the pipeline that is documented, as well as the `__call__` method that is not documented by default. If you just want to add additional methods that are not documented, you can put the list of all methods to add in a list that contains `all`.
140
+
141
+ ```
142
+ [[autodoc]] XXXPipeline
143
+ - all
144
+ - __call__
145
+ - enable_attention_slicing
146
+ - disable_attention_slicing
147
+ - enable_xformers_memory_efficient_attention
148
+ - disable_xformers_memory_efficient_attention
149
+ ```
150
+
151
+ You can follow the same process to create a new scheduler under the `docs/source/api/schedulers` folder
152
+
153
+ ### Writing source documentation
154
+
155
+ Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names
156
+ and objects like True, None, or any strings should usually be put in `code`.
157
+
158
+ When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool
159
+ adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or
160
+ function to be in the main package.
161
+
162
+ If you want to create a link to some internal class or function, you need to
163
+ provide its path. For instance: \[\`pipelines.ImagePipelineOutput\`\]. This will be converted into a link with
164
+ `pipelines.ImagePipelineOutput` in the description. To get rid of the path and only keep the name of the object you are
165
+ linking to in the description, add a ~: \[\`~pipelines.ImagePipelineOutput\`\] will generate a link with `ImagePipelineOutput` in the description.
166
+
167
+ The same works for methods so you can either use \[\`XXXClass.method\`\] or \[~\`XXXClass.method\`\].
168
+
169
+ #### Defining arguments in a method
170
+
171
+ Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and
172
+ an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its
173
+ description:
174
+
175
+ ```
176
+ Args:
177
+ n_layers (`int`): The number of layers of the model.
178
+ ```
179
+
180
+ If the description is too long to fit in one line, another indentation is necessary before writing the description
181
+ after the argument.
182
+
183
+ Here's an example showcasing everything so far:
184
+
185
+ ```
186
+ Args:
187
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
188
+ Indices of input sequence tokens in the vocabulary.
189
+
190
+ Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and
191
+ [`~PreTrainedTokenizer.__call__`] for details.
192
+
193
+ [What are input IDs?](../glossary#input-ids)
194
+ ```
195
+
196
+ For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the
197
+ following signature:
198
+
199
+ ```
200
+ def my_function(x: str = None, a: float = 1):
201
+ ```
202
+
203
+ then its documentation should look like this:
204
+
205
+ ```
206
+ Args:
207
+ x (`str`, *optional*):
208
+ This argument controls ...
209
+ a (`float`, *optional*, defaults to 1):
210
+ This argument is used to ...
211
+ ```
212
+
213
+ Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even
214
+ if the first line describing your argument type and its default gets long, you can't break it on several lines. You can
215
+ however write as many lines as you want in the indented description (see the example above with `input_ids`).
216
+
217
+ #### Writing a multi-line code block
218
+
219
+ Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown:
220
+
221
+
222
+ ````
223
+ ```
224
+ # first line of code
225
+ # second line
226
+ # etc
227
+ ```
228
+ ````
229
+
230
+ #### Writing a return block
231
+
232
+ The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation.
233
+ The first line should be the type of the return, followed by a line return. No need to indent further for the elements
234
+ building the return.
235
+
236
+ Here's an example of a single value return:
237
+
238
+ ```
239
+ Returns:
240
+ `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.
241
+ ```
242
+
243
+ Here's an example of a tuple return, comprising several objects:
244
+
245
+ ```
246
+ Returns:
247
+ `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
248
+ - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
249
+ Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
250
+ - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
251
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
252
+ ```
253
+
254
+ #### Adding an image
255
+
256
+ Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
257
+ the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference
258
+ them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
259
+ If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
260
+ to this dataset.
261
+
262
+ ## Styling the docstring
263
+
264
+ We have an automatic script running with the `make style` command that will make sure that:
265
+ - the docstrings fully take advantage of the line width
266
+ - all code examples are formatted using black, like the code of the Transformers library
267
+
268
+ This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's
269
+ recommended to commit your changes before running `make style`, so you can revert the changes done by that script
270
+ easily.
271
+
diffusers/docs/TRANSLATING.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Translating the Diffusers documentation into your language
2
+
3
+ As part of our mission to democratize machine learning, we'd love to make the Diffusers library available in many more languages! Follow the steps below if you want to help translate the documentation into your language 🙏.
4
+
5
+ **🗞️ Open an issue**
6
+
7
+ To get started, navigate to the [Issues](https://github.com/huggingface/diffusers/issues) page of this repo and check if anyone else has opened an issue for your language. If not, open a new issue by selecting the "Translation template" from the "New issue" button.
8
+
9
+ Once an issue exists, post a comment to indicate which chapters you'd like to work on, and we'll add your name to the list.
10
+
11
+
12
+ **🍴 Fork the repository**
13
+
14
+ First, you'll need to [fork the Diffusers repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). You can do this by clicking on the **Fork** button on the top-right corner of this repo's page.
15
+
16
+ Once you've forked the repo, you'll want to get the files on your local machine for editing. You can do that by cloning the fork with Git as follows:
17
+
18
+ ```bash
19
+ git clone https://github.com/YOUR-USERNAME/diffusers.git
20
+ ```
21
+
22
+ **📋 Copy-paste the English version with a new language code**
23
+
24
+ The documentation files are in one leading directory:
25
+
26
+ - [`docs/source`](https://github.com/huggingface/diffusers/tree/main/docs/source): All the documentation materials are organized here by language.
27
+
28
+ You'll only need to copy the files in the [`docs/source/en`](https://github.com/huggingface/diffusers/tree/main/docs/source/en) directory, so first navigate to your fork of the repo and run the following:
29
+
30
+ ```bash
31
+ cd ~/path/to/diffusers/docs
32
+ cp -r source/en source/LANG-ID
33
+ ```
34
+
35
+ Here, `LANG-ID` should be one of the ISO 639-1 or ISO 639-2 language codes -- see [here](https://www.loc.gov/standards/iso639-2/php/code_list.php) for a handy table.
36
+
37
+ **✍️ Start translating**
38
+
39
+ The fun part comes - translating the text!
40
+
41
+ The first thing we recommend is translating the part of the `_toctree.yml` file that corresponds to your doc chapter. This file is used to render the table of contents on the website.
42
+
43
+ > 🙋 If the `_toctree.yml` file doesn't yet exist for your language, you can create one by copy-pasting from the English version and deleting the sections unrelated to your chapter. Just make sure it exists in the `docs/source/LANG-ID/` directory!
44
+
45
+ The fields you should add are `local` (with the name of the file containing the translation; e.g. `autoclass_tutorial`), and `title` (with the title of the doc in your language; e.g. `Load pretrained instances with an AutoClass`) -- as a reference, here is the `_toctree.yml` for [English](https://github.com/huggingface/diffusers/blob/main/docs/source/en/_toctree.yml):
46
+
47
+ ```yaml
48
+ - sections:
49
+ - local: pipeline_tutorial # Do not change this! Use the same name for your .md file
50
+ title: Pipelines for inference # Translate this!
51
+ ...
52
+ title: Tutorials # Translate this!
53
+ ```
54
+
55
+ Once you have translated the `_toctree.yml` file, you can start translating the [MDX](https://mdxjs.com/) files associated with your docs chapter.
56
+
57
+ > 🙋 If you'd like others to help you with the translation, you should [open an issue](https://github.com/huggingface/diffusers/issues) and tag @patrickvonplaten.
diffusers/docs/source/en/_toctree.yml ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🧨 Diffusers
4
+ - local: quicktour
5
+ title: Quicktour
6
+ - local: stable_diffusion
7
+ title: Stable Diffusion
8
+ - local: installation
9
+ title: Installation
10
+ title: Get started
11
+ - sections:
12
+ - sections:
13
+ - local: using-diffusers/loading
14
+ title: Loading Pipelines, Models, and Schedulers
15
+ - local: using-diffusers/schedulers
16
+ title: Using different Schedulers
17
+ - local: using-diffusers/configuration
18
+ title: Configuring Pipelines, Models, and Schedulers
19
+ - local: using-diffusers/custom_pipeline_overview
20
+ title: Loading and Adding Custom Pipelines
21
+ - local: using-diffusers/kerascv
22
+ title: Using KerasCV Stable Diffusion Checkpoints in Diffusers
23
+ title: Loading & Hub
24
+ - sections:
25
+ - local: using-diffusers/unconditional_image_generation
26
+ title: Unconditional Image Generation
27
+ - local: using-diffusers/conditional_image_generation
28
+ title: Text-to-Image Generation
29
+ - local: using-diffusers/img2img
30
+ title: Text-Guided Image-to-Image
31
+ - local: using-diffusers/inpaint
32
+ title: Text-Guided Image-Inpainting
33
+ - local: using-diffusers/depth2img
34
+ title: Text-Guided Depth-to-Image
35
+ - local: using-diffusers/reusing_seeds
36
+ title: Reusing seeds for deterministic generation
37
+ - local: using-diffusers/reproducibility
38
+ title: Reproducibility
39
+ - local: using-diffusers/custom_pipeline_examples
40
+ title: Community Pipelines
41
+ - local: using-diffusers/contribute_pipeline
42
+ title: How to contribute a Pipeline
43
+ - local: using-diffusers/using_safetensors
44
+ title: Using safetensors
45
+ title: Pipelines for Inference
46
+ - sections:
47
+ - local: using-diffusers/rl
48
+ title: Reinforcement Learning
49
+ - local: using-diffusers/audio
50
+ title: Audio
51
+ - local: using-diffusers/other-modalities
52
+ title: Other Modalities
53
+ title: Taking Diffusers Beyond Images
54
+ title: Using Diffusers
55
+ - sections:
56
+ - local: optimization/fp16
57
+ title: Memory and Speed
58
+ - local: optimization/xformers
59
+ title: xFormers
60
+ - local: optimization/onnx
61
+ title: ONNX
62
+ - local: optimization/open_vino
63
+ title: OpenVINO
64
+ - local: optimization/mps
65
+ title: MPS
66
+ - local: optimization/habana
67
+ title: Habana Gaudi
68
+ title: Optimization/Special Hardware
69
+ - sections:
70
+ - local: training/overview
71
+ title: Overview
72
+ - local: training/unconditional_training
73
+ title: Unconditional Image Generation
74
+ - local: training/text_inversion
75
+ title: Textual Inversion
76
+ - local: training/dreambooth
77
+ title: Dreambooth
78
+ - local: training/text2image
79
+ title: Text-to-image fine-tuning
80
+ - local: training/lora
81
+ title: LoRA Support in Diffusers
82
+ title: Training
83
+ - sections:
84
+ - local: conceptual/philosophy
85
+ title: Philosophy
86
+ - local: conceptual/contribution
87
+ title: How to contribute?
88
+ - local: conceptual/ethical_guidelines
89
+ title: Diffusers' Ethical Guidelines
90
+ title: Conceptual Guides
91
+ - sections:
92
+ - sections:
93
+ - local: api/models
94
+ title: Models
95
+ - local: api/diffusion_pipeline
96
+ title: Diffusion Pipeline
97
+ - local: api/logging
98
+ title: Logging
99
+ - local: api/configuration
100
+ title: Configuration
101
+ - local: api/outputs
102
+ title: Outputs
103
+ - local: api/loaders
104
+ title: Loaders
105
+ title: Main Classes
106
+ - sections:
107
+ - local: api/pipelines/overview
108
+ title: Overview
109
+ - local: api/pipelines/alt_diffusion
110
+ title: AltDiffusion
111
+ - local: api/pipelines/audio_diffusion
112
+ title: Audio Diffusion
113
+ - local: api/pipelines/cycle_diffusion
114
+ title: Cycle Diffusion
115
+ - local: api/pipelines/dance_diffusion
116
+ title: Dance Diffusion
117
+ - local: api/pipelines/ddim
118
+ title: DDIM
119
+ - local: api/pipelines/ddpm
120
+ title: DDPM
121
+ - local: api/pipelines/dit
122
+ title: DiT
123
+ - local: api/pipelines/latent_diffusion
124
+ title: Latent Diffusion
125
+ - local: api/pipelines/paint_by_example
126
+ title: PaintByExample
127
+ - local: api/pipelines/pndm
128
+ title: PNDM
129
+ - local: api/pipelines/repaint
130
+ title: RePaint
131
+ - local: api/pipelines/stable_diffusion_safe
132
+ title: Safe Stable Diffusion
133
+ - local: api/pipelines/score_sde_ve
134
+ title: Score SDE VE
135
+ - sections:
136
+ - local: api/pipelines/stable_diffusion/overview
137
+ title: Overview
138
+ - local: api/pipelines/stable_diffusion/text2img
139
+ title: Text-to-Image
140
+ - local: api/pipelines/stable_diffusion/img2img
141
+ title: Image-to-Image
142
+ - local: api/pipelines/stable_diffusion/inpaint
143
+ title: Inpaint
144
+ - local: api/pipelines/stable_diffusion/depth2img
145
+ title: Depth-to-Image
146
+ - local: api/pipelines/stable_diffusion/image_variation
147
+ title: Image-Variation
148
+ - local: api/pipelines/stable_diffusion/upscale
149
+ title: Super-Resolution
150
+ - local: api/pipelines/stable_diffusion/latent_upscale
151
+ title: Stable-Diffusion-Latent-Upscaler
152
+ - local: api/pipelines/stable_diffusion/pix2pix
153
+ title: InstructPix2Pix
154
+ title: Stable Diffusion
155
+ - local: api/pipelines/stable_diffusion_2
156
+ title: Stable Diffusion 2
157
+ - local: api/pipelines/stochastic_karras_ve
158
+ title: Stochastic Karras VE
159
+ - local: api/pipelines/unclip
160
+ title: UnCLIP
161
+ - local: api/pipelines/latent_diffusion_uncond
162
+ title: Unconditional Latent Diffusion
163
+ - local: api/pipelines/versatile_diffusion
164
+ title: Versatile Diffusion
165
+ - local: api/pipelines/vq_diffusion
166
+ title: VQ Diffusion
167
+ title: Pipelines
168
+ - sections:
169
+ - local: api/schedulers/overview
170
+ title: Overview
171
+ - local: api/schedulers/ddim
172
+ title: DDIM
173
+ - local: api/schedulers/ddpm
174
+ title: DDPM
175
+ - local: api/schedulers/deis
176
+ title: DEIS
177
+ - local: api/schedulers/dpm_discrete
178
+ title: DPM Discrete Scheduler
179
+ - local: api/schedulers/dpm_discrete_ancestral
180
+ title: DPM Discrete Scheduler with ancestral sampling
181
+ - local: api/schedulers/euler_ancestral
182
+ title: Euler Ancestral Scheduler
183
+ - local: api/schedulers/euler
184
+ title: Euler scheduler
185
+ - local: api/schedulers/heun
186
+ title: Heun Scheduler
187
+ - local: api/schedulers/ipndm
188
+ title: IPNDM
189
+ - local: api/schedulers/lms_discrete
190
+ title: Linear Multistep
191
+ - local: api/schedulers/multistep_dpm_solver
192
+ title: Multistep DPM-Solver
193
+ - local: api/schedulers/pndm
194
+ title: PNDM
195
+ - local: api/schedulers/repaint
196
+ title: RePaint Scheduler
197
+ - local: api/schedulers/singlestep_dpm_solver
198
+ title: Singlestep DPM-Solver
199
+ - local: api/schedulers/stochastic_karras_ve
200
+ title: Stochastic Kerras VE
201
+ - local: api/schedulers/score_sde_ve
202
+ title: VE-SDE
203
+ - local: api/schedulers/score_sde_vp
204
+ title: VP-SDE
205
+ - local: api/schedulers/vq_diffusion
206
+ title: VQDiffusionScheduler
207
+ title: Schedulers
208
+ - sections:
209
+ - local: api/experimental/rl
210
+ title: RL Planning
211
+ title: Experimental Features
212
+ title: API
diffusers/docs/source/en/api/configuration.mdx ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Configuration
14
+
15
+ In Diffusers, schedulers of type [`schedulers.scheduling_utils.SchedulerMixin`], and models of type [`ModelMixin`] inherit from [`ConfigMixin`] which conveniently takes care of storing all parameters that are
16
+ passed to the respective `__init__` methods in a JSON-configuration file.
17
+
18
+ ## ConfigMixin
19
+
20
+ [[autodoc]] ConfigMixin
21
+ - load_config
22
+ - from_config
23
+ - save_config
diffusers/docs/source/en/api/diffusion_pipeline.mdx ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Pipelines
14
+
15
+ The [`DiffusionPipeline`] is the easiest way to load any pretrained diffusion pipeline from the [Hub](https://huggingface.co/models?library=diffusers) and to use it in inference.
16
+
17
+ <Tip>
18
+
19
+ One should not use the Diffusion Pipeline class for training or fine-tuning a diffusion model. Individual
20
+ components of diffusion pipelines are usually trained individually, so we suggest to directly work
21
+ with [`UNetModel`] and [`UNetConditionModel`].
22
+
23
+ </Tip>
24
+
25
+ Any diffusion pipeline that is loaded with [`~DiffusionPipeline.from_pretrained`] will automatically
26
+ detect the pipeline type, *e.g.* [`StableDiffusionPipeline`] and consequently load each component of the
27
+ pipeline and pass them into the `__init__` function of the pipeline, *e.g.* [`~StableDiffusionPipeline.__init__`].
28
+
29
+ Any pipeline object can be saved locally with [`~DiffusionPipeline.save_pretrained`].
30
+
31
+ ## DiffusionPipeline
32
+ [[autodoc]] DiffusionPipeline
33
+ - all
34
+ - __call__
35
+ - device
36
+ - to
37
+ - components
38
+
39
+ ## ImagePipelineOutput
40
+ By default diffusion pipelines return an object of class
41
+
42
+ [[autodoc]] pipelines.ImagePipelineOutput
43
+
44
+ ## AudioPipelineOutput
45
+ By default diffusion pipelines return an object of class
46
+
47
+ [[autodoc]] pipelines.AudioPipelineOutput
diffusers/docs/source/en/api/experimental/rl.mdx ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # TODO
14
+
15
+ Coming soon!
diffusers/docs/source/en/api/loaders.mdx ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Loaders
14
+
15
+ There are many ways to train adapter neural networks for diffusion models, such as
16
+ - [Textual Inversion](./training/text_inversion.mdx)
17
+ - [LoRA](https://github.com/cloneofsimo/lora)
18
+ - [Hypernetworks](https://arxiv.org/abs/1609.09106)
19
+
20
+ Such adapter neural networks often only consist of a fraction of the number of weights compared
21
+ to the pretrained model and as such are very portable. The Diffusers library offers an easy-to-use
22
+ API to load such adapter neural networks via the [`loaders.py` module](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders.py).
23
+
24
+ **Note**: This module is still highly experimental and prone to future changes.
25
+
26
+ ## LoaderMixins
27
+
28
+ ### UNet2DConditionLoadersMixin
29
+
30
+ [[autodoc]] loaders.UNet2DConditionLoadersMixin
diffusers/docs/source/en/api/logging.mdx ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Logging
14
+
15
+ 🧨 Diffusers has a centralized logging system, so that you can setup the verbosity of the library easily.
16
+
17
+ Currently the default verbosity of the library is `WARNING`.
18
+
19
+ To change the level of verbosity, just use one of the direct setters. For instance, here is how to change the verbosity
20
+ to the INFO level.
21
+
22
+ ```python
23
+ import diffusers
24
+
25
+ diffusers.logging.set_verbosity_info()
26
+ ```
27
+
28
+ You can also use the environment variable `DIFFUSERS_VERBOSITY` to override the default verbosity. You can set it
29
+ to one of the following: `debug`, `info`, `warning`, `error`, `critical`. For example:
30
+
31
+ ```bash
32
+ DIFFUSERS_VERBOSITY=error ./myprogram.py
33
+ ```
34
+
35
+ Additionally, some `warnings` can be disabled by setting the environment variable
36
+ `DIFFUSERS_NO_ADVISORY_WARNINGS` to a true value, like *1*. This will disable any warning that is logged using
37
+ [`logger.warning_advice`]. For example:
38
+
39
+ ```bash
40
+ DIFFUSERS_NO_ADVISORY_WARNINGS=1 ./myprogram.py
41
+ ```
42
+
43
+ Here is an example of how to use the same logger as the library in your own module or script:
44
+
45
+ ```python
46
+ from diffusers.utils import logging
47
+
48
+ logging.set_verbosity_info()
49
+ logger = logging.get_logger("diffusers")
50
+ logger.info("INFO")
51
+ logger.warning("WARN")
52
+ ```
53
+
54
+
55
+ All the methods of this logging module are documented below, the main ones are
56
+ [`logging.get_verbosity`] to get the current level of verbosity in the logger and
57
+ [`logging.set_verbosity`] to set the verbosity to the level of your choice. In order (from the least
58
+ verbose to the most verbose), those levels (with their corresponding int values in parenthesis) are:
59
+
60
+ - `diffusers.logging.CRITICAL` or `diffusers.logging.FATAL` (int value, 50): only report the most
61
+ critical errors.
62
+ - `diffusers.logging.ERROR` (int value, 40): only report errors.
63
+ - `diffusers.logging.WARNING` or `diffusers.logging.WARN` (int value, 30): only reports error and
64
+ warnings. This the default level used by the library.
65
+ - `diffusers.logging.INFO` (int value, 20): reports error, warnings and basic information.
66
+ - `diffusers.logging.DEBUG` (int value, 10): report all information.
67
+
68
+ By default, `tqdm` progress bars will be displayed during model download. [`logging.disable_progress_bar`] and [`logging.enable_progress_bar`] can be used to suppress or unsuppress this behavior.
69
+
70
+ ## Base setters
71
+
72
+ [[autodoc]] logging.set_verbosity_error
73
+
74
+ [[autodoc]] logging.set_verbosity_warning
75
+
76
+ [[autodoc]] logging.set_verbosity_info
77
+
78
+ [[autodoc]] logging.set_verbosity_debug
79
+
80
+ ## Other functions
81
+
82
+ [[autodoc]] logging.get_verbosity
83
+
84
+ [[autodoc]] logging.set_verbosity
85
+
86
+ [[autodoc]] logging.get_logger
87
+
88
+ [[autodoc]] logging.enable_default_handler
89
+
90
+ [[autodoc]] logging.disable_default_handler
91
+
92
+ [[autodoc]] logging.enable_explicit_format
93
+
94
+ [[autodoc]] logging.reset_format
95
+
96
+ [[autodoc]] logging.enable_progress_bar
97
+
98
+ [[autodoc]] logging.disable_progress_bar
diffusers/docs/source/en/api/models.mdx ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Models
14
+
15
+ Diffusers contains pretrained models for popular algorithms and modules for creating the next set of diffusion models.
16
+ The primary function of these models is to denoise an input sample, by modeling the distribution $p_\theta(\mathbf{x}_{t-1}|\mathbf{x}_t)$.
17
+ The models are built on the base class ['ModelMixin'] that is a `torch.nn.module` with basic functionality for saving and loading models both locally and from the HuggingFace hub.
18
+
19
+ ## ModelMixin
20
+ [[autodoc]] ModelMixin
21
+
22
+ ## UNet2DOutput
23
+ [[autodoc]] models.unet_2d.UNet2DOutput
24
+
25
+ ## UNet2DModel
26
+ [[autodoc]] UNet2DModel
27
+
28
+ ## UNet1DOutput
29
+ [[autodoc]] models.unet_1d.UNet1DOutput
30
+
31
+ ## UNet1DModel
32
+ [[autodoc]] UNet1DModel
33
+
34
+ ## UNet2DConditionOutput
35
+ [[autodoc]] models.unet_2d_condition.UNet2DConditionOutput
36
+
37
+ ## UNet2DConditionModel
38
+ [[autodoc]] UNet2DConditionModel
39
+
40
+ ## DecoderOutput
41
+ [[autodoc]] models.vae.DecoderOutput
42
+
43
+ ## VQEncoderOutput
44
+ [[autodoc]] models.vq_model.VQEncoderOutput
45
+
46
+ ## VQModel
47
+ [[autodoc]] VQModel
48
+
49
+ ## AutoencoderKLOutput
50
+ [[autodoc]] models.autoencoder_kl.AutoencoderKLOutput
51
+
52
+ ## AutoencoderKL
53
+ [[autodoc]] AutoencoderKL
54
+
55
+ ## Transformer2DModel
56
+ [[autodoc]] Transformer2DModel
57
+
58
+ ## Transformer2DModelOutput
59
+ [[autodoc]] models.transformer_2d.Transformer2DModelOutput
60
+
61
+ ## PriorTransformer
62
+ [[autodoc]] models.prior_transformer.PriorTransformer
63
+
64
+ ## PriorTransformerOutput
65
+ [[autodoc]] models.prior_transformer.PriorTransformerOutput
66
+
67
+ ## FlaxModelMixin
68
+ [[autodoc]] FlaxModelMixin
69
+
70
+ ## FlaxUNet2DConditionOutput
71
+ [[autodoc]] models.unet_2d_condition_flax.FlaxUNet2DConditionOutput
72
+
73
+ ## FlaxUNet2DConditionModel
74
+ [[autodoc]] FlaxUNet2DConditionModel
75
+
76
+ ## FlaxDecoderOutput
77
+ [[autodoc]] models.vae_flax.FlaxDecoderOutput
78
+
79
+ ## FlaxAutoencoderKLOutput
80
+ [[autodoc]] models.vae_flax.FlaxAutoencoderKLOutput
81
+
82
+ ## FlaxAutoencoderKL
83
+ [[autodoc]] FlaxAutoencoderKL
diffusers/docs/source/en/api/outputs.mdx ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # BaseOutputs
14
+
15
+ All models have outputs that are instances of subclasses of [`~utils.BaseOutput`]. Those are
16
+ data structures containing all the information returned by the model, but that can also be used as tuples or
17
+ dictionaries.
18
+
19
+ Let's see how this looks in an example:
20
+
21
+ ```python
22
+ from diffusers import DDIMPipeline
23
+
24
+ pipeline = DDIMPipeline.from_pretrained("google/ddpm-cifar10-32")
25
+ outputs = pipeline()
26
+ ```
27
+
28
+ The `outputs` object is a [`~pipelines.ImagePipelineOutput`], as we can see in the
29
+ documentation of that class below, it means it has an image attribute.
30
+
31
+ You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you will get `None`:
32
+
33
+ ```python
34
+ outputs.images
35
+ ```
36
+
37
+ or via keyword lookup
38
+
39
+ ```python
40
+ outputs["images"]
41
+ ```
42
+
43
+ When considering our `outputs` object as tuple, it only considers the attributes that don't have `None` values.
44
+ Here for instance, we could retrieve images via indexing:
45
+
46
+ ```python
47
+ outputs[:1]
48
+ ```
49
+
50
+ which will return the tuple `(outputs.images)` for instance.
51
+
52
+ ## BaseOutput
53
+
54
+ [[autodoc]] utils.BaseOutput
55
+ - to_tuple
diffusers/docs/source/en/api/pipelines/alt_diffusion.mdx ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # AltDiffusion
14
+
15
+ AltDiffusion was proposed in [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679) by Zhongzhi Chen, Guang Liu, Bo-Wen Zhang, Fulong Ye, Qinghong Yang, Ledell Wu
16
+
17
+ The abstract of the paper is the following:
18
+
19
+ *In this work, we present a conceptually simple and effective method to train a strong bilingual multimodal representation model. Starting from the pretrained multimodal representation model CLIP released by OpenAI, we switched its text encoder with a pretrained multilingual text encoder XLM-R, and aligned both languages and image representations by a two-stage training schema consisting of teacher learning and contrastive learning. We validate our method through evaluations of a wide range of tasks. We set new state-of-the-art performances on a bunch of tasks including ImageNet-CN, Flicker30k- CN, and COCO-CN. Further, we obtain very close performances with CLIP on almost all tasks, suggesting that one can simply alter the text encoder in CLIP for extended capabilities such as multilingual understanding.*
20
+
21
+
22
+ *Overview*:
23
+
24
+ | Pipeline | Tasks | Colab | Demo
25
+ |---|---|:---:|:---:|
26
+ | [pipeline_alt_diffusion.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py) | *Text-to-Image Generation* | - | -
27
+ | [pipeline_alt_diffusion_img2img.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py) | *Image-to-Image Text-Guided Generation* | - |-
28
+
29
+ ## Tips
30
+
31
+ - AltDiffusion is conceptually exaclty the same as [Stable Diffusion](./api/pipelines/stable_diffusion/overview).
32
+
33
+ - *Run AltDiffusion*
34
+
35
+ AltDiffusion can be tested very easily with the [`AltDiffusionPipeline`], [`AltDiffusionImg2ImgPipeline`] and the `"BAAI/AltDiffusion-m9"` checkpoint exactly in the same way it is shown in the [Conditional Image Generation Guide](./using-diffusers/conditional_image_generation) and the [Image-to-Image Generation Guide](./using-diffusers/img2img).
36
+
37
+ - *How to load and use different schedulers.*
38
+
39
+ The alt diffusion pipeline uses [`DDIMScheduler`] scheduler by default. But `diffusers` provides many other schedulers that can be used with the alt diffusion pipeline such as [`PNDMScheduler`], [`LMSDiscreteScheduler`], [`EulerDiscreteScheduler`], [`EulerAncestralDiscreteScheduler`] etc.
40
+ To use a different scheduler, you can either change it via the [`ConfigMixin.from_config`] method or pass the `scheduler` argument to the `from_pretrained` method of the pipeline. For example, to use the [`EulerDiscreteScheduler`], you can do the following:
41
+
42
+ ```python
43
+ >>> from diffusers import AltDiffusionPipeline, EulerDiscreteScheduler
44
+
45
+ >>> pipeline = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion-m9")
46
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
47
+
48
+ >>> # or
49
+ >>> euler_scheduler = EulerDiscreteScheduler.from_pretrained("BAAI/AltDiffusion-m9", subfolder="scheduler")
50
+ >>> pipeline = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion-m9", scheduler=euler_scheduler)
51
+ ```
52
+
53
+
54
+ - *How to convert all use cases with multiple or single pipeline*
55
+
56
+ If you want to use all possible use cases in a single `DiffusionPipeline` we recommend using the `components` functionality to instantiate all components in the most memory-efficient way:
57
+
58
+ ```python
59
+ >>> from diffusers import (
60
+ ... AltDiffusionPipeline,
61
+ ... AltDiffusionImg2ImgPipeline,
62
+ ... )
63
+
64
+ >>> text2img = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion-m9")
65
+ >>> img2img = AltDiffusionImg2ImgPipeline(**text2img.components)
66
+
67
+ >>> # now you can use text2img(...) and img2img(...) just like the call methods of each respective pipeline
68
+ ```
69
+
70
+ ## AltDiffusionPipelineOutput
71
+ [[autodoc]] pipelines.alt_diffusion.AltDiffusionPipelineOutput
72
+ - all
73
+ - __call__
74
+
75
+ ## AltDiffusionPipeline
76
+ [[autodoc]] AltDiffusionPipeline
77
+ - all
78
+ - __call__
79
+
80
+ ## AltDiffusionImg2ImgPipeline
81
+ [[autodoc]] AltDiffusionImg2ImgPipeline
82
+ - all
83
+ - __call__
diffusers/docs/source/en/api/pipelines/audio_diffusion.mdx ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Audio Diffusion
14
+
15
+ ## Overview
16
+
17
+ [Audio Diffusion](https://github.com/teticio/audio-diffusion) by Robert Dargavel Smith.
18
+
19
+ Audio Diffusion leverages the recent advances in image generation using diffusion models by converting audio samples to
20
+ and from mel spectrogram images.
21
+
22
+ The original codebase of this implementation can be found [here](https://github.com/teticio/audio-diffusion), including
23
+ training scripts and example notebooks.
24
+
25
+ ## Available Pipelines:
26
+
27
+ | Pipeline | Tasks | Colab
28
+ |---|---|:---:|
29
+ | [pipeline_audio_diffusion.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/audio_diffusion/pipeline_audio_diffusion.py) | *Unconditional Audio Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/teticio/audio-diffusion/blob/master/notebooks/audio_diffusion_pipeline.ipynb) |
30
+
31
+
32
+ ## Examples:
33
+
34
+ ### Audio Diffusion
35
+
36
+ ```python
37
+ import torch
38
+ from IPython.display import Audio
39
+ from diffusers import DiffusionPipeline
40
+
41
+ device = "cuda" if torch.cuda.is_available() else "cpu"
42
+ pipe = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-256").to(device)
43
+
44
+ output = pipe()
45
+ display(output.images[0])
46
+ display(Audio(output.audios[0], rate=mel.get_sample_rate()))
47
+ ```
48
+
49
+ ### Latent Audio Diffusion
50
+
51
+ ```python
52
+ import torch
53
+ from IPython.display import Audio
54
+ from diffusers import DiffusionPipeline
55
+
56
+ device = "cuda" if torch.cuda.is_available() else "cpu"
57
+ pipe = DiffusionPipeline.from_pretrained("teticio/latent-audio-diffusion-256").to(device)
58
+
59
+ output = pipe()
60
+ display(output.images[0])
61
+ display(Audio(output.audios[0], rate=pipe.mel.get_sample_rate()))
62
+ ```
63
+
64
+ ### Audio Diffusion with DDIM (faster)
65
+
66
+ ```python
67
+ import torch
68
+ from IPython.display import Audio
69
+ from diffusers import DiffusionPipeline
70
+
71
+ device = "cuda" if torch.cuda.is_available() else "cpu"
72
+ pipe = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256").to(device)
73
+
74
+ output = pipe()
75
+ display(output.images[0])
76
+ display(Audio(output.audios[0], rate=pipe.mel.get_sample_rate()))
77
+ ```
78
+
79
+ ### Variations, in-painting, out-painting etc.
80
+
81
+ ```python
82
+ output = pipe(
83
+ raw_audio=output.audios[0, 0],
84
+ start_step=int(pipe.get_default_steps() / 2),
85
+ mask_start_secs=1,
86
+ mask_end_secs=1,
87
+ )
88
+ display(output.images[0])
89
+ display(Audio(output.audios[0], rate=pipe.mel.get_sample_rate()))
90
+ ```
91
+
92
+ ## AudioDiffusionPipeline
93
+ [[autodoc]] AudioDiffusionPipeline
94
+ - all
95
+ - __call__
96
+
97
+ ## Mel
98
+ [[autodoc]] Mel
diffusers/docs/source/en/api/pipelines/cycle_diffusion.mdx ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Cycle Diffusion
14
+
15
+ ## Overview
16
+
17
+ Cycle Diffusion is a Text-Guided Image-to-Image Generation model proposed in [Unifying Diffusion Models' Latent Space, with Applications to CycleDiffusion and Guidance](https://arxiv.org/abs/2210.05559) by Chen Henry Wu, Fernando De la Torre.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *Diffusion models have achieved unprecedented performance in generative modeling. The commonly-adopted formulation of the latent code of diffusion models is a sequence of gradually denoised samples, as opposed to the simpler (e.g., Gaussian) latent space of GANs, VAEs, and normalizing flows. This paper provides an alternative, Gaussian formulation of the latent space of various diffusion models, as well as an invertible DPM-Encoder that maps images into the latent space. While our formulation is purely based on the definition of diffusion models, we demonstrate several intriguing consequences. (1) Empirically, we observe that a common latent space emerges from two diffusion models trained independently on related domains. In light of this finding, we propose CycleDiffusion, which uses DPM-Encoder for unpaired image-to-image translation. Furthermore, applying CycleDiffusion to text-to-image diffusion models, we show that large-scale text-to-image diffusion models can be used as zero-shot image-to-image editors. (2) One can guide pre-trained diffusion models and GANs by controlling the latent codes in a unified, plug-and-play formulation based on energy-based models. Using the CLIP model and a face recognition model as guidance, we demonstrate that diffusion models have better coverage of low-density sub-populations and individuals than GANs.*
22
+
23
+ *Tips*:
24
+ - The Cycle Diffusion pipeline is fully compatible with any [Stable Diffusion](./stable_diffusion) checkpoints
25
+ - Currently Cycle Diffusion only works with the [`DDIMScheduler`].
26
+
27
+ *Example*:
28
+
29
+ In the following we should how to best use the [`CycleDiffusionPipeline`]
30
+
31
+ ```python
32
+ import requests
33
+ import torch
34
+ from PIL import Image
35
+ from io import BytesIO
36
+
37
+ from diffusers import CycleDiffusionPipeline, DDIMScheduler
38
+
39
+ # load the pipeline
40
+ # make sure you're logged in with `huggingface-cli login`
41
+ model_id_or_path = "CompVis/stable-diffusion-v1-4"
42
+ scheduler = DDIMScheduler.from_pretrained(model_id_or_path, subfolder="scheduler")
43
+ pipe = CycleDiffusionPipeline.from_pretrained(model_id_or_path, scheduler=scheduler).to("cuda")
44
+
45
+ # let's download an initial image
46
+ url = "https://raw.githubusercontent.com/ChenWu98/cycle-diffusion/main/data/dalle2/An%20astronaut%20riding%20a%20horse.png"
47
+ response = requests.get(url)
48
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
49
+ init_image = init_image.resize((512, 512))
50
+ init_image.save("horse.png")
51
+
52
+ # let's specify a prompt
53
+ source_prompt = "An astronaut riding a horse"
54
+ prompt = "An astronaut riding an elephant"
55
+
56
+ # call the pipeline
57
+ image = pipe(
58
+ prompt=prompt,
59
+ source_prompt=source_prompt,
60
+ image=init_image,
61
+ num_inference_steps=100,
62
+ eta=0.1,
63
+ strength=0.8,
64
+ guidance_scale=2,
65
+ source_guidance_scale=1,
66
+ ).images[0]
67
+
68
+ image.save("horse_to_elephant.png")
69
+
70
+ # let's try another example
71
+ # See more samples at the original repo: https://github.com/ChenWu98/cycle-diffusion
72
+ url = "https://raw.githubusercontent.com/ChenWu98/cycle-diffusion/main/data/dalle2/A%20black%20colored%20car.png"
73
+ response = requests.get(url)
74
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
75
+ init_image = init_image.resize((512, 512))
76
+ init_image.save("black.png")
77
+
78
+ source_prompt = "A black colored car"
79
+ prompt = "A blue colored car"
80
+
81
+ # call the pipeline
82
+ torch.manual_seed(0)
83
+ image = pipe(
84
+ prompt=prompt,
85
+ source_prompt=source_prompt,
86
+ image=init_image,
87
+ num_inference_steps=100,
88
+ eta=0.1,
89
+ strength=0.85,
90
+ guidance_scale=3,
91
+ source_guidance_scale=1,
92
+ ).images[0]
93
+
94
+ image.save("black_to_blue.png")
95
+ ```
96
+
97
+ ## CycleDiffusionPipeline
98
+ [[autodoc]] CycleDiffusionPipeline
99
+ - all
100
+ - __call__
diffusers/docs/source/en/api/pipelines/dance_diffusion.mdx ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Dance Diffusion
14
+
15
+ ## Overview
16
+
17
+ [Dance Diffusion](https://github.com/Harmonai-org/sample-generator) by Zach Evans.
18
+
19
+ Dance Diffusion is the first in a suite of generative audio tools for producers and musicians to be released by Harmonai.
20
+ For more info or to get involved in the development of these tools, please visit https://harmonai.org and fill out the form on the front page.
21
+
22
+ The original codebase of this implementation can be found [here](https://github.com/Harmonai-org/sample-generator).
23
+
24
+ ## Available Pipelines:
25
+
26
+ | Pipeline | Tasks | Colab
27
+ |---|---|:---:|
28
+ | [pipeline_dance_diffusion.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py) | *Unconditional Audio Generation* | - |
29
+
30
+
31
+ ## DanceDiffusionPipeline
32
+ [[autodoc]] DanceDiffusionPipeline
33
+ - all
34
+ - __call__
diffusers/docs/source/en/api/pipelines/ddim.mdx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # DDIM
14
+
15
+ ## Overview
16
+
17
+ [Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502) (DDIM) by Jiaming Song, Chenlin Meng and Stefano Ermon.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ Denoising diffusion probabilistic models (DDPMs) have achieved high quality image generation without adversarial training, yet they require simulating a Markov chain for many steps to produce a sample. To accelerate sampling, we present denoising diffusion implicit models (DDIMs), a more efficient class of iterative implicit probabilistic models with the same training procedure as DDPMs. In DDPMs, the generative process is defined as the reverse of a Markovian diffusion process. We construct a class of non-Markovian diffusion processes that lead to the same training objective, but whose reverse process can be much faster to sample from. We empirically demonstrate that DDIMs can produce high quality samples 10× to 50× faster in terms of wall-clock time compared to DDPMs, allow us to trade off computation for sample quality, and can perform semantically meaningful image interpolation directly in the latent space.
22
+
23
+ The original codebase of this paper can be found here: [ermongroup/ddim](https://github.com/ermongroup/ddim).
24
+ For questions, feel free to contact the author on [tsong.me](https://tsong.me/).
25
+
26
+ ## Available Pipelines:
27
+
28
+ | Pipeline | Tasks | Colab
29
+ |---|---|:---:|
30
+ | [pipeline_ddim.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddim/pipeline_ddim.py) | *Unconditional Image Generation* | - |
31
+
32
+
33
+ ## DDIMPipeline
34
+ [[autodoc]] DDIMPipeline
35
+ - all
36
+ - __call__
diffusers/docs/source/en/api/pipelines/ddpm.mdx ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # DDPM
14
+
15
+ ## Overview
16
+
17
+ [Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239)
18
+ (DDPM) by Jonathan Ho, Ajay Jain and Pieter Abbeel proposes the diffusion based model of the same name, but in the context of the 🤗 Diffusers library, DDPM refers to the discrete denoising scheduler from the paper as well as the pipeline.
19
+
20
+ The abstract of the paper is the following:
21
+
22
+ We present high quality image synthesis results using diffusion probabilistic models, a class of latent variable models inspired by considerations from nonequilibrium thermodynamics. Our best results are obtained by training on a weighted variational bound designed according to a novel connection between diffusion probabilistic models and denoising score matching with Langevin dynamics, and our models naturally admit a progressive lossy decompression scheme that can be interpreted as a generalization of autoregressive decoding. On the unconditional CIFAR10 dataset, we obtain an Inception score of 9.46 and a state-of-the-art FID score of 3.17. On 256x256 LSUN, we obtain sample quality similar to ProgressiveGAN.
23
+
24
+ The original codebase of this paper can be found [here](https://github.com/hojonathanho/diffusion).
25
+
26
+
27
+ ## Available Pipelines:
28
+
29
+ | Pipeline | Tasks | Colab
30
+ |---|---|:---:|
31
+ | [pipeline_ddpm.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddpm/pipeline_ddpm.py) | *Unconditional Image Generation* | - |
32
+
33
+
34
+ # DDPMPipeline
35
+ [[autodoc]] DDPMPipeline
36
+ - all
37
+ - __call__
diffusers/docs/source/en/api/pipelines/dit.mdx ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Scalable Diffusion Models with Transformers (DiT)
14
+
15
+ ## Overview
16
+
17
+ [Scalable Diffusion Models with Transformers](https://arxiv.org/abs/2212.09748) (DiT) by William Peebles and Saining Xie.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *We explore a new class of diffusion models based on the transformer architecture. We train latent diffusion models of images, replacing the commonly-used U-Net backbone with a transformer that operates on latent patches. We analyze the scalability of our Diffusion Transformers (DiTs) through the lens of forward pass complexity as measured by Gflops. We find that DiTs with higher Gflops -- through increased transformer depth/width or increased number of input tokens -- consistently have lower FID. In addition to possessing good scalability properties, our largest DiT-XL/2 models outperform all prior diffusion models on the class-conditional ImageNet 512x512 and 256x256 benchmarks, achieving a state-of-the-art FID of 2.27 on the latter.*
22
+
23
+ The original codebase of this paper can be found here: [facebookresearch/dit](https://github.com/facebookresearch/dit).
24
+
25
+ ## Available Pipelines:
26
+
27
+ | Pipeline | Tasks | Colab
28
+ |---|---|:---:|
29
+ | [pipeline_dit.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/dit/pipeline_dit.py) | *Conditional Image Generation* | - |
30
+
31
+
32
+ ## Usage example
33
+
34
+ ```python
35
+ from diffusers import DiTPipeline, DPMSolverMultistepScheduler
36
+ import torch
37
+
38
+ pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256", torch_dtype=torch.float16)
39
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
40
+ pipe = pipe.to("cuda")
41
+
42
+ # pick words from Imagenet class labels
43
+ pipe.labels # to print all available words
44
+
45
+ # pick words that exist in ImageNet
46
+ words = ["white shark", "umbrella"]
47
+
48
+ class_ids = pipe.get_label_ids(words)
49
+
50
+ generator = torch.manual_seed(33)
51
+ output = pipe(class_labels=class_ids, num_inference_steps=25, generator=generator)
52
+
53
+ image = output.images[0] # label 'white shark'
54
+ ```
55
+
56
+ ## DiTPipeline
57
+ [[autodoc]] DiTPipeline
58
+ - all
59
+ - __call__
diffusers/docs/source/en/api/pipelines/latent_diffusion.mdx ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Latent Diffusion
14
+
15
+ ## Overview
16
+
17
+ Latent Diffusion was proposed in [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) by Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, Björn Ommer.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *By decomposing the image formation process into a sequential application of denoising autoencoders, diffusion models (DMs) achieve state-of-the-art synthesis results on image data and beyond. Additionally, their formulation allows for a guiding mechanism to control the image generation process without retraining. However, since these models typically operate directly in pixel space, optimization of powerful DMs often consumes hundreds of GPU days and inference is expensive due to sequential evaluations. To enable DM training on limited computational resources while retaining their quality and flexibility, we apply them in the latent space of powerful pretrained autoencoders. In contrast to previous work, training diffusion models on such a representation allows for the first time to reach a near-optimal point between complexity reduction and detail preservation, greatly boosting visual fidelity. By introducing cross-attention layers into the model architecture, we turn diffusion models into powerful and flexible generators for general conditioning inputs such as text or bounding boxes and high-resolution synthesis becomes possible in a convolutional manner. Our latent diffusion models (LDMs) achieve a new state of the art for image inpainting and highly competitive performance on various tasks, including unconditional image generation, semantic scene synthesis, and super-resolution, while significantly reducing computational requirements compared to pixel-based DMs.*
22
+
23
+ The original codebase can be found [here](https://github.com/CompVis/latent-diffusion).
24
+
25
+ ## Tips:
26
+
27
+ -
28
+ -
29
+ -
30
+
31
+ ## Available Pipelines:
32
+
33
+ | Pipeline | Tasks | Colab
34
+ |---|---|:---:|
35
+ | [pipeline_latent_diffusion.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py) | *Text-to-Image Generation* | - |
36
+ | [pipeline_latent_diffusion_superresolution.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py) | *Super Resolution* | - |
37
+
38
+ ## Examples:
39
+
40
+
41
+ ## LDMTextToImagePipeline
42
+ [[autodoc]] LDMTextToImagePipeline
43
+ - all
44
+ - __call__
45
+
46
+ ## LDMSuperResolutionPipeline
47
+ [[autodoc]] LDMSuperResolutionPipeline
48
+ - all
49
+ - __call__
diffusers/docs/source/en/api/pipelines/latent_diffusion_uncond.mdx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Unconditional Latent Diffusion
14
+
15
+ ## Overview
16
+
17
+ Unconditional Latent Diffusion was proposed in [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) by Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, Björn Ommer.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *By decomposing the image formation process into a sequential application of denoising autoencoders, diffusion models (DMs) achieve state-of-the-art synthesis results on image data and beyond. Additionally, their formulation allows for a guiding mechanism to control the image generation process without retraining. However, since these models typically operate directly in pixel space, optimization of powerful DMs often consumes hundreds of GPU days and inference is expensive due to sequential evaluations. To enable DM training on limited computational resources while retaining their quality and flexibility, we apply them in the latent space of powerful pretrained autoencoders. In contrast to previous work, training diffusion models on such a representation allows for the first time to reach a near-optimal point between complexity reduction and detail preservation, greatly boosting visual fidelity. By introducing cross-attention layers into the model architecture, we turn diffusion models into powerful and flexible generators for general conditioning inputs such as text or bounding boxes and high-resolution synthesis becomes possible in a convolutional manner. Our latent diffusion models (LDMs) achieve a new state of the art for image inpainting and highly competitive performance on various tasks, including unconditional image generation, semantic scene synthesis, and super-resolution, while significantly reducing computational requirements compared to pixel-based DMs.*
22
+
23
+ The original codebase can be found [here](https://github.com/CompVis/latent-diffusion).
24
+
25
+ ## Tips:
26
+
27
+ -
28
+ -
29
+ -
30
+
31
+ ## Available Pipelines:
32
+
33
+ | Pipeline | Tasks | Colab
34
+ |---|---|:---:|
35
+ | [pipeline_latent_diffusion_uncond.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py) | *Unconditional Image Generation* | - |
36
+
37
+ ## Examples:
38
+
39
+ ## LDMPipeline
40
+ [[autodoc]] LDMPipeline
41
+ - all
42
+ - __call__
diffusers/docs/source/en/api/pipelines/overview.mdx ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Pipelines
14
+
15
+ Pipelines provide a simple way to run state-of-the-art diffusion models in inference.
16
+ Most diffusion systems consist of multiple independently-trained models and highly adaptable scheduler
17
+ components - all of which are needed to have a functioning end-to-end diffusion system.
18
+
19
+ As an example, [Stable Diffusion](https://huggingface.co/blog/stable_diffusion) has three independently trained models:
20
+ - [Autoencoder](./api/models#vae)
21
+ - [Conditional Unet](./api/models#UNet2DConditionModel)
22
+ - [CLIP text encoder](https://huggingface.co/docs/transformers/v4.21.2/en/model_doc/clip#transformers.CLIPTextModel)
23
+ - a scheduler component, [scheduler](./api/scheduler#pndm),
24
+ - a [CLIPFeatureExtractor](https://huggingface.co/docs/transformers/v4.21.2/en/model_doc/clip#transformers.CLIPFeatureExtractor),
25
+ - as well as a [safety checker](./stable_diffusion#safety_checker).
26
+ All of these components are necessary to run stable diffusion in inference even though they were trained
27
+ or created independently from each other.
28
+
29
+ To that end, we strive to offer all open-sourced, state-of-the-art diffusion system under a unified API.
30
+ More specifically, we strive to provide pipelines that
31
+ - 1. can load the officially published weights and yield 1-to-1 the same outputs as the original implementation according to the corresponding paper (*e.g.* [LDMTextToImagePipeline](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/latent_diffusion), uses the officially released weights of [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752)),
32
+ - 2. have a simple user interface to run the model in inference (see the [Pipelines API](#pipelines-api) section),
33
+ - 3. are easy to understand with code that is self-explanatory and can be read along-side the official paper (see [Pipelines summary](#pipelines-summary)),
34
+ - 4. can easily be contributed by the community (see the [Contribution](#contribution) section).
35
+
36
+ **Note** that pipelines do not (and should not) offer any training functionality.
37
+ If you are looking for *official* training examples, please have a look at [examples](https://github.com/huggingface/diffusers/tree/main/examples).
38
+
39
+ ## 🧨 Diffusers Summary
40
+
41
+ The following table summarizes all officially supported pipelines, their corresponding paper, and if
42
+ available a colab notebook to directly try them out.
43
+
44
+
45
+ | Pipeline | Paper | Tasks | Colab
46
+ |---|---|:---:|:---:|
47
+ | [alt_diffusion](./alt_diffusion) | [**AltDiffusion**](https://arxiv.org/abs/2211.06679) | Image-to-Image Text-Guided Generation | -
48
+ | [audio_diffusion](./audio_diffusion) | [**Audio Diffusion**](https://github.com/teticio/audio_diffusion.git) | Unconditional Audio Generation |
49
+ | [cycle_diffusion](./cycle_diffusion) | [**Cycle Diffusion**](https://arxiv.org/abs/2210.05559) | Image-to-Image Text-Guided Generation |
50
+ | [dance_diffusion](./dance_diffusion) | [**Dance Diffusion**](https://github.com/williamberman/diffusers.git) | Unconditional Audio Generation |
51
+ | [ddpm](./ddpm) | [**Denoising Diffusion Probabilistic Models**](https://arxiv.org/abs/2006.11239) | Unconditional Image Generation |
52
+ | [ddim](./ddim) | [**Denoising Diffusion Implicit Models**](https://arxiv.org/abs/2010.02502) | Unconditional Image Generation |
53
+ | [latent_diffusion](./latent_diffusion) | [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://arxiv.org/abs/2112.10752)| Text-to-Image Generation |
54
+ | [latent_diffusion](./latent_diffusion) | [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://arxiv.org/abs/2112.10752)| Super Resolution Image-to-Image |
55
+ | [latent_diffusion_uncond](./latent_diffusion_uncond) | [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://arxiv.org/abs/2112.10752) | Unconditional Image Generation |
56
+ | [paint_by_example](./paint_by_example) | [**Paint by Example: Exemplar-based Image Editing with Diffusion Models**](https://arxiv.org/abs/2211.13227) | Image-Guided Image Inpainting |
57
+ | [pndm](./pndm) | [**Pseudo Numerical Methods for Diffusion Models on Manifolds**](https://arxiv.org/abs/2202.09778) | Unconditional Image Generation |
58
+ | [score_sde_ve](./score_sde_ve) | [**Score-Based Generative Modeling through Stochastic Differential Equations**](https://openreview.net/forum?id=PxTIG12RRHS) | Unconditional Image Generation |
59
+ | [score_sde_vp](./score_sde_vp) | [**Score-Based Generative Modeling through Stochastic Differential Equations**](https://openreview.net/forum?id=PxTIG12RRHS) | Unconditional Image Generation |
60
+ | [stable_diffusion](./stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | Text-to-Image Generation | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb)
61
+ | [stable_diffusion](./stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | Image-to-Image Text-Guided Generation | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb)
62
+ | [stable_diffusion](./stable_diffusion) | [**Stable Diffusion**](https://stability.ai/blog/stable-diffusion-public-release) | Text-Guided Image Inpainting | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/in_painting_with_stable_diffusion_using_diffusers.ipynb)
63
+ | [stable_diffusion_2](./stable_diffusion_2) | [**Stable Diffusion 2**](https://stability.ai/blog/stable-diffusion-v2-release) | Text-to-Image Generation |
64
+ | [stable_diffusion_2](./stable_diffusion_2) | [**Stable Diffusion 2**](https://stability.ai/blog/stable-diffusion-v2-release) | Text-Guided Image Inpainting |
65
+ | [stable_diffusion_2](./stable_diffusion_2) | [**Stable Diffusion 2**](https://stability.ai/blog/stable-diffusion-v2-release) | Text-Guided Super Resolution Image-to-Image |
66
+ | [stable_diffusion_safe](./stable_diffusion_safe) | [**Safe Stable Diffusion**](https://arxiv.org/abs/2211.05105) | Text-Guided Generation | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ml-research/safe-latent-diffusion/blob/main/examples/Safe%20Latent%20Diffusion.ipynb)
67
+ | [stochastic_karras_ve](./stochastic_karras_ve) | [**Elucidating the Design Space of Diffusion-Based Generative Models**](https://arxiv.org/abs/2206.00364) | Unconditional Image Generation |
68
+ | [unclip](./unclip) | [Hierarchical Text-Conditional Image Generation with CLIP Latents](https://arxiv.org/abs/2204.06125) | Text-to-Image Generation |
69
+ | [versatile_diffusion](./versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://arxiv.org/abs/2211.08332) | Text-to-Image Generation |
70
+ | [versatile_diffusion](./versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://arxiv.org/abs/2211.08332) | Image Variations Generation |
71
+ | [versatile_diffusion](./versatile_diffusion) | [Versatile Diffusion: Text, Images and Variations All in One Diffusion Model](https://arxiv.org/abs/2211.08332) | Dual Image and Text Guided Generation |
72
+ | [vq_diffusion](./vq_diffusion) | [Vector Quantized Diffusion Model for Text-to-Image Synthesis](https://arxiv.org/abs/2111.14822) | Text-to-Image Generation |
73
+
74
+
75
+ **Note**: Pipelines are simple examples of how to play around with the diffusion systems as described in the corresponding papers.
76
+
77
+ However, most of them can be adapted to use different scheduler components or even different model components. Some pipeline examples are shown in the [Examples](#examples) below.
78
+
79
+ ## Pipelines API
80
+
81
+ Diffusion models often consist of multiple independently-trained models or other previously existing components.
82
+
83
+
84
+ Each model has been trained independently on a different task and the scheduler can easily be swapped out and replaced with a different one.
85
+ During inference, we however want to be able to easily load all components and use them in inference - even if one component, *e.g.* CLIP's text encoder, originates from a different library, such as [Transformers](https://github.com/huggingface/transformers). To that end, all pipelines provide the following functionality:
86
+
87
+ - [`from_pretrained` method](../diffusion_pipeline) that accepts a Hugging Face Hub repository id, *e.g.* [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5) or a path to a local directory, *e.g.*
88
+ "./stable-diffusion". To correctly retrieve which models and components should be loaded, one has to provide a `model_index.json` file, *e.g.* [runwayml/stable-diffusion-v1-5/model_index.json](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/model_index.json), which defines all components that should be
89
+ loaded into the pipelines. More specifically, for each model/component one needs to define the format `<name>: ["<library>", "<class name>"]`. `<name>` is the attribute name given to the loaded instance of `<class name>` which can be found in the library or pipeline folder called `"<library>"`.
90
+ - [`save_pretrained`](../diffusion_pipeline) that accepts a local path, *e.g.* `./stable-diffusion` under which all models/components of the pipeline will be saved. For each component/model a folder is created inside the local path that is named after the given attribute name, *e.g.* `./stable_diffusion/unet`.
91
+ In addition, a `model_index.json` file is created at the root of the local path, *e.g.* `./stable_diffusion/model_index.json` so that the complete pipeline can again be instantiated
92
+ from the local path.
93
+ - [`to`](../diffusion_pipeline) which accepts a `string` or `torch.device` to move all models that are of type `torch.nn.Module` to the passed device. The behavior is fully analogous to [PyTorch's `to` method](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.to).
94
+ - [`__call__`] method to use the pipeline in inference. `__call__` defines inference logic of the pipeline and should ideally encompass all aspects of it, from pre-processing to forwarding tensors to the different models and schedulers, as well as post-processing. The API of the `__call__` method can strongly vary from pipeline to pipeline. *E.g.* a text-to-image pipeline, such as [`StableDiffusionPipeline`](./stable_diffusion) should accept among other things the text prompt to generate the image. A pure image generation pipeline, such as [DDPMPipeline](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/ddpm) on the other hand can be run without providing any inputs. To better understand what inputs can be adapted for
95
+ each pipeline, one should look directly into the respective pipeline.
96
+
97
+ **Note**: All pipelines have PyTorch's autograd disabled by decorating the `__call__` method with a [`torch.no_grad`](https://pytorch.org/docs/stable/generated/torch.no_grad.html) decorator because pipelines should
98
+ not be used for training. If you want to store the gradients during the forward pass, we recommend writing your own pipeline, see also our [community-examples](https://github.com/huggingface/diffusers/tree/main/examples/community)
99
+
100
+ ## Contribution
101
+
102
+ We are more than happy about any contribution to the officially supported pipelines 🤗. We aspire
103
+ all of our pipelines to be **self-contained**, **easy-to-tweak**, **beginner-friendly** and for **one-purpose-only**.
104
+
105
+ - **Self-contained**: A pipeline shall be as self-contained as possible. More specifically, this means that all functionality should be either directly defined in the pipeline file itself, should be inherited from (and only from) the [`DiffusionPipeline` class](.../diffusion_pipeline) or be directly attached to the model and scheduler components of the pipeline.
106
+ - **Easy-to-use**: Pipelines should be extremely easy to use - one should be able to load the pipeline and
107
+ use it for its designated task, *e.g.* text-to-image generation, in just a couple of lines of code. Most
108
+ logic including pre-processing, an unrolled diffusion loop, and post-processing should all happen inside the `__call__` method.
109
+ - **Easy-to-tweak**: Certain pipelines will not be able to handle all use cases and tasks that you might like them to. If you want to use a certain pipeline for a specific use case that is not yet supported, you might have to copy the pipeline file and tweak the code to your needs. We try to make the pipeline code as readable as possible so that each part –from pre-processing to diffusing to post-processing– can easily be adapted. If you would like the community to benefit from your customized pipeline, we would love to see a contribution to our [community-examples](https://github.com/huggingface/diffusers/tree/main/examples/community). If you feel that an important pipeline should be part of the official pipelines but isn't, a contribution to the [official pipelines](./overview) would be even better.
110
+ - **One-purpose-only**: Pipelines should be used for one task and one task only. Even if two tasks are very similar from a modeling point of view, *e.g.* image2image translation and in-painting, pipelines shall be used for one task only to keep them *easy-to-tweak* and *readable*.
111
+
112
+ ## Examples
113
+
114
+ ### Text-to-Image generation with Stable Diffusion
115
+
116
+ ```python
117
+ # make sure you're logged in with `huggingface-cli login`
118
+ from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
119
+
120
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
121
+ pipe = pipe.to("cuda")
122
+
123
+ prompt = "a photo of an astronaut riding a horse on mars"
124
+ image = pipe(prompt).images[0]
125
+
126
+ image.save("astronaut_rides_horse.png")
127
+ ```
128
+
129
+ ### Image-to-Image text-guided generation with Stable Diffusion
130
+
131
+ The `StableDiffusionImg2ImgPipeline` lets you pass a text prompt and an initial image to condition the generation of new images.
132
+
133
+ ```python
134
+ import requests
135
+ from PIL import Image
136
+ from io import BytesIO
137
+
138
+ from diffusers import StableDiffusionImg2ImgPipeline
139
+
140
+ # load the pipeline
141
+ device = "cuda"
142
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16).to(
143
+ device
144
+ )
145
+
146
+ # let's download an initial image
147
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
148
+
149
+ response = requests.get(url)
150
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
151
+ init_image = init_image.resize((768, 512))
152
+
153
+ prompt = "A fantasy landscape, trending on artstation"
154
+
155
+ images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
156
+
157
+ images[0].save("fantasy_landscape.png")
158
+ ```
159
+ You can also run this example on colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb)
160
+
161
+ ### Tweak prompts reusing seeds and latents
162
+
163
+ You can generate your own latents to reproduce results, or tweak your prompt on a specific result you liked. [This notebook](https://github.com/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb) shows how to do it step by step. You can also run it in Google Colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb).
164
+
165
+
166
+ ### In-painting using Stable Diffusion
167
+
168
+ The `StableDiffusionInpaintPipeline` lets you edit specific parts of an image by providing a mask and text prompt.
169
+
170
+ ```python
171
+ import PIL
172
+ import requests
173
+ import torch
174
+ from io import BytesIO
175
+
176
+ from diffusers import StableDiffusionInpaintPipeline
177
+
178
+
179
+ def download_image(url):
180
+ response = requests.get(url)
181
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
182
+
183
+
184
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
185
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
186
+
187
+ init_image = download_image(img_url).resize((512, 512))
188
+ mask_image = download_image(mask_url).resize((512, 512))
189
+
190
+ pipe = StableDiffusionInpaintPipeline.from_pretrained(
191
+ "runwayml/stable-diffusion-inpainting",
192
+ torch_dtype=torch.float16,
193
+ )
194
+ pipe = pipe.to("cuda")
195
+
196
+ prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
197
+ image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
198
+ ```
199
+
200
+ You can also run this example on colab [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/in_painting_with_stable_diffusion_using_diffusers.ipynb)
diffusers/docs/source/en/api/pipelines/paint_by_example.mdx ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # PaintByExample
14
+
15
+ ## Overview
16
+
17
+ [Paint by Example: Exemplar-based Image Editing with Diffusion Models](https://arxiv.org/abs/2211.13227) by Binxin Yang, Shuyang Gu, Bo Zhang, Ting Zhang, Xuejin Chen, Xiaoyan Sun, Dong Chen, Fang Wen
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *Language-guided image editing has achieved great success recently. In this paper, for the first time, we investigate exemplar-guided image editing for more precise control. We achieve this goal by leveraging self-supervised training to disentangle and re-organize the source image and the exemplar. However, the naive approach will cause obvious fusing artifacts. We carefully analyze it and propose an information bottleneck and strong augmentations to avoid the trivial solution of directly copying and pasting the exemplar image. Meanwhile, to ensure the controllability of the editing process, we design an arbitrary shape mask for the exemplar image and leverage the classifier-free guidance to increase the similarity to the exemplar image. The whole framework involves a single forward of the diffusion model without any iterative optimization. We demonstrate that our method achieves an impressive performance and enables controllable editing on in-the-wild images with high fidelity.*
22
+
23
+ The original codebase can be found [here](https://github.com/Fantasy-Studio/Paint-by-Example).
24
+
25
+ ## Available Pipelines:
26
+
27
+ | Pipeline | Tasks | Colab
28
+ |---|---|:---:|
29
+ | [pipeline_paint_by_example.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py) | *Image-Guided Image Painting* | - |
30
+
31
+ ## Tips
32
+
33
+ - PaintByExample is supported by the official [Fantasy-Studio/Paint-by-Example](https://huggingface.co/Fantasy-Studio/Paint-by-Example) checkpoint. The checkpoint has been warm-started from the [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4) and with the objective to inpaint partly masked images conditioned on example / reference images
34
+ - To quickly demo *PaintByExample*, please have a look at [this demo](https://huggingface.co/spaces/Fantasy-Studio/Paint-by-Example)
35
+ - You can run the following code snippet as an example:
36
+
37
+
38
+ ```python
39
+ # !pip install diffusers transformers
40
+
41
+ import PIL
42
+ import requests
43
+ import torch
44
+ from io import BytesIO
45
+ from diffusers import DiffusionPipeline
46
+
47
+
48
+ def download_image(url):
49
+ response = requests.get(url)
50
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
51
+
52
+
53
+ img_url = "https://raw.githubusercontent.com/Fantasy-Studio/Paint-by-Example/main/examples/image/example_1.png"
54
+ mask_url = "https://raw.githubusercontent.com/Fantasy-Studio/Paint-by-Example/main/examples/mask/example_1.png"
55
+ example_url = "https://raw.githubusercontent.com/Fantasy-Studio/Paint-by-Example/main/examples/reference/example_1.jpg"
56
+
57
+ init_image = download_image(img_url).resize((512, 512))
58
+ mask_image = download_image(mask_url).resize((512, 512))
59
+ example_image = download_image(example_url).resize((512, 512))
60
+
61
+ pipe = DiffusionPipeline.from_pretrained(
62
+ "Fantasy-Studio/Paint-by-Example",
63
+ torch_dtype=torch.float16,
64
+ )
65
+ pipe = pipe.to("cuda")
66
+
67
+ image = pipe(image=init_image, mask_image=mask_image, example_image=example_image).images[0]
68
+ image
69
+ ```
70
+
71
+ ## PaintByExamplePipeline
72
+ [[autodoc]] PaintByExamplePipeline
73
+ - all
74
+ - __call__
diffusers/docs/source/en/api/pipelines/pndm.mdx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # PNDM
14
+
15
+ ## Overview
16
+
17
+ [Pseudo Numerical methods for Diffusion Models on manifolds](https://arxiv.org/abs/2202.09778) (PNDM) by Luping Liu, Yi Ren, Zhijie Lin and Zhou Zhao.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ Denoising Diffusion Probabilistic Models (DDPMs) can generate high-quality samples such as image and audio samples. However, DDPMs require hundreds to thousands of iterations to produce final samples. Several prior works have successfully accelerated DDPMs through adjusting the variance schedule (e.g., Improved Denoising Diffusion Probabilistic Models) or the denoising equation (e.g., Denoising Diffusion Implicit Models (DDIMs)). However, these acceleration methods cannot maintain the quality of samples and even introduce new noise at a high speedup rate, which limit their practicability. To accelerate the inference process while keeping the sample quality, we provide a fresh perspective that DDPMs should be treated as solving differential equations on manifolds. Under such a perspective, we propose pseudo numerical methods for diffusion models (PNDMs). Specifically, we figure out how to solve differential equations on manifolds and show that DDIMs are simple cases of pseudo numerical methods. We change several classical numerical methods to corresponding pseudo numerical methods and find that the pseudo linear multi-step method is the best in most situations. According to our experiments, by directly using pre-trained models on Cifar10, CelebA and LSUN, PNDMs can generate higher quality synthetic images with only 50 steps compared with 1000-step DDIMs (20x speedup), significantly outperform DDIMs with 250 steps (by around 0.4 in FID) and have good generalization on different variance schedules.
22
+
23
+ The original codebase can be found [here](https://github.com/luping-liu/PNDM).
24
+
25
+ ## Available Pipelines:
26
+
27
+ | Pipeline | Tasks | Colab
28
+ |---|---|:---:|
29
+ | [pipeline_pndm.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pndm/pipeline_pndm.py) | *Unconditional Image Generation* | - |
30
+
31
+
32
+ ## PNDMPipeline
33
+ [[autodoc]] PNDMPipeline
34
+ - all
35
+ - __call__
diffusers/docs/source/en/api/pipelines/repaint.mdx ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # RePaint
14
+
15
+ ## Overview
16
+
17
+ [RePaint: Inpainting using Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2201.09865) (PNDM) by Andreas Lugmayr, Martin Danelljan, Andres Romero, Fisher Yu, Radu Timofte, Luc Van Gool.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ Free-form inpainting is the task of adding new content to an image in the regions specified by an arbitrary binary mask. Most existing approaches train for a certain distribution of masks, which limits their generalization capabilities to unseen mask types. Furthermore, training with pixel-wise and perceptual losses often leads to simple textural extensions towards the missing areas instead of semantically meaningful generation. In this work, we propose RePaint: A Denoising Diffusion Probabilistic Model (DDPM) based inpainting approach that is applicable to even extreme masks. We employ a pretrained unconditional DDPM as the generative prior. To condition the generation process, we only alter the reverse diffusion iterations by sampling the unmasked regions using the given image information. Since this technique does not modify or condition the original DDPM network itself, the model produces high-quality and diverse output images for any inpainting form. We validate our method for both faces and general-purpose image inpainting using standard and extreme masks.
22
+ RePaint outperforms state-of-the-art Autoregressive, and GAN approaches for at least five out of six mask distributions.
23
+
24
+ The original codebase can be found [here](https://github.com/andreas128/RePaint).
25
+
26
+ ## Available Pipelines:
27
+
28
+ | Pipeline | Tasks | Colab
29
+ |-------------------------------------------------------------------------------------------------------------------------------|--------------------|:---:|
30
+ | [pipeline_repaint.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/repaint/pipeline_repaint.py) | *Image Inpainting* | - |
31
+
32
+ ## Usage example
33
+
34
+ ```python
35
+ from io import BytesIO
36
+
37
+ import torch
38
+
39
+ import PIL
40
+ import requests
41
+ from diffusers import RePaintPipeline, RePaintScheduler
42
+
43
+
44
+ def download_image(url):
45
+ response = requests.get(url)
46
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
47
+
48
+
49
+ img_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/celeba_hq_256.png"
50
+ mask_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"
51
+
52
+ # Load the original image and the mask as PIL images
53
+ original_image = download_image(img_url).resize((256, 256))
54
+ mask_image = download_image(mask_url).resize((256, 256))
55
+
56
+ # Load the RePaint scheduler and pipeline based on a pretrained DDPM model
57
+ scheduler = RePaintScheduler.from_pretrained("google/ddpm-ema-celebahq-256")
58
+ pipe = RePaintPipeline.from_pretrained("google/ddpm-ema-celebahq-256", scheduler=scheduler)
59
+ pipe = pipe.to("cuda")
60
+
61
+ generator = torch.Generator(device="cuda").manual_seed(0)
62
+ output = pipe(
63
+ original_image=original_image,
64
+ mask_image=mask_image,
65
+ num_inference_steps=250,
66
+ eta=0.0,
67
+ jump_length=10,
68
+ jump_n_sample=10,
69
+ generator=generator,
70
+ )
71
+ inpainted_image = output.images[0]
72
+ ```
73
+
74
+ ## RePaintPipeline
75
+ [[autodoc]] RePaintPipeline
76
+ - all
77
+ - __call__
diffusers/docs/source/en/api/pipelines/score_sde_ve.mdx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Score SDE VE
14
+
15
+ ## Overview
16
+
17
+ [Score-Based Generative Modeling through Stochastic Differential Equations](https://arxiv.org/abs/2011.13456) (Score SDE) by Yang Song, Jascha Sohl-Dickstein, Diederik P. Kingma, Abhishek Kumar, Stefano Ermon and Ben Poole.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ Creating noise from data is easy; creating data from noise is generative modeling. We present a stochastic differential equation (SDE) that smoothly transforms a complex data distribution to a known prior distribution by slowly injecting noise, and a corresponding reverse-time SDE that transforms the prior distribution back into the data distribution by slowly removing the noise. Crucially, the reverse-time SDE depends only on the time-dependent gradient field (\aka, score) of the perturbed data distribution. By leveraging advances in score-based generative modeling, we can accurately estimate these scores with neural networks, and use numerical SDE solvers to generate samples. We show that this framework encapsulates previous approaches in score-based generative modeling and diffusion probabilistic modeling, allowing for new sampling procedures and new modeling capabilities. In particular, we introduce a predictor-corrector framework to correct errors in the evolution of the discretized reverse-time SDE. We also derive an equivalent neural ODE that samples from the same distribution as the SDE, but additionally enables exact likelihood computation, and improved sampling efficiency. In addition, we provide a new way to solve inverse problems with score-based models, as demonstrated with experiments on class-conditional generation, image inpainting, and colorization. Combined with multiple architectural improvements, we achieve record-breaking performance for unconditional image generation on CIFAR-10 with an Inception score of 9.89 and FID of 2.20, a competitive likelihood of 2.99 bits/dim, and demonstrate high fidelity generation of 1024 x 1024 images for the first time from a score-based generative model.
22
+
23
+ The original codebase can be found [here](https://github.com/yang-song/score_sde_pytorch).
24
+
25
+ This pipeline implements the Variance Expanding (VE) variant of the method.
26
+
27
+ ## Available Pipelines:
28
+
29
+ | Pipeline | Tasks | Colab
30
+ |---|---|:---:|
31
+ | [pipeline_score_sde_ve.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py) | *Unconditional Image Generation* | - |
32
+
33
+ ## ScoreSdeVePipeline
34
+ [[autodoc]] ScoreSdeVePipeline
35
+ - all
36
+ - __call__
diffusers/docs/source/en/api/pipelines/stable_diffusion/depth2img.mdx ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Depth-to-Image Generation
14
+
15
+ ## StableDiffusionDepth2ImgPipeline
16
+
17
+ The depth-guided stable diffusion model was created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), and [LAION](https://laion.ai/), as part of Stable Diffusion 2.0. It uses [MiDas](https://github.com/isl-org/MiDaS) to infer depth based on an image.
18
+
19
+ [`StableDiffusionDepth2ImgPipeline`] lets you pass a text prompt and an initial image to condition the generation of new images as well as a `depth_map` to preserve the images’ structure.
20
+
21
+ The original codebase can be found here:
22
+ - *Stable Diffusion v2*: [Stability-AI/stablediffusion](https://github.com/Stability-AI/stablediffusion#depth-conditional-stable-diffusion)
23
+
24
+ Available Checkpoints are:
25
+ - *stable-diffusion-2-depth*: [stabilityai/stable-diffusion-2-depth](https://huggingface.co/stabilityai/stable-diffusion-2-depth)
26
+
27
+ [[autodoc]] StableDiffusionDepth2ImgPipeline
28
+ - all
29
+ - __call__
30
+ - enable_attention_slicing
31
+ - disable_attention_slicing
32
+ - enable_xformers_memory_efficient_attention
33
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/image_variation.mdx ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Image Variation
14
+
15
+ ## StableDiffusionImageVariationPipeline
16
+
17
+ [`StableDiffusionImageVariationPipeline`] lets you generate variations from an input image using Stable Diffusion. It uses a fine-tuned version of Stable Diffusion model, trained by [Justin Pinkney](https://www.justinpinkney.com/) (@Buntworthy) at [Lambda](https://lambdalabs.com/)
18
+
19
+ The original codebase can be found here:
20
+ [Stable Diffusion Image Variations](https://github.com/LambdaLabsML/lambda-diffusers#stable-diffusion-image-variations)
21
+
22
+ Available Checkpoints are:
23
+ - *sd-image-variations-diffusers*: [lambdalabs/sd-image-variations-diffusers](https://huggingface.co/lambdalabs/sd-image-variations-diffusers)
24
+
25
+ [[autodoc]] StableDiffusionImageVariationPipeline
26
+ - all
27
+ - __call__
28
+ - enable_attention_slicing
29
+ - disable_attention_slicing
30
+ - enable_xformers_memory_efficient_attention
31
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/img2img.mdx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Image-to-Image Generation
14
+
15
+ ## StableDiffusionImg2ImgPipeline
16
+
17
+ The Stable Diffusion model was created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), [runway](https://github.com/runwayml), and [LAION](https://laion.ai/). The [`StableDiffusionImg2ImgPipeline`] lets you pass a text prompt and an initial image to condition the generation of new images using Stable Diffusion.
18
+
19
+ The original codebase can be found here: [CampVis/stable-diffusion](https://github.com/CompVis/stable-diffusion/blob/main/scripts/img2img.py)
20
+
21
+ [`StableDiffusionImg2ImgPipeline`] is compatible with all Stable Diffusion checkpoints for [Text-to-Image](./text2img)
22
+
23
+ [[autodoc]] StableDiffusionImg2ImgPipeline
24
+ - all
25
+ - __call__
26
+ - enable_attention_slicing
27
+ - disable_attention_slicing
28
+ - enable_xformers_memory_efficient_attention
29
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/inpaint.mdx ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Text-Guided Image Inpainting
14
+
15
+ ## StableDiffusionInpaintPipeline
16
+
17
+ The Stable Diffusion model was created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), [runway](https://github.com/runwayml), and [LAION](https://laion.ai/). The [`StableDiffusionInpaintPipeline`] lets you edit specific parts of an image by providing a mask and a text prompt using Stable Diffusion.
18
+
19
+ The original codebase can be found here:
20
+ - *Stable Diffusion V1*: [CampVis/stable-diffusion](https://github.com/runwayml/stable-diffusion#inpainting-with-stable-diffusion)
21
+ - *Stable Diffusion V2*: [Stability-AI/stablediffusion](https://github.com/Stability-AI/stablediffusion#image-inpainting-with-stable-diffusion)
22
+
23
+ Available checkpoints are:
24
+ - *stable-diffusion-inpainting (512x512 resolution)*: [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting)
25
+ - *stable-diffusion-2-inpainting (512x512 resolution)*: [stabilityai/stable-diffusion-2-inpainting](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting)
26
+
27
+ [[autodoc]] StableDiffusionInpaintPipeline
28
+ - all
29
+ - __call__
30
+ - enable_attention_slicing
31
+ - disable_attention_slicing
32
+ - enable_xformers_memory_efficient_attention
33
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/latent_upscale.mdx ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stable Diffusion Latent Upscaler
14
+
15
+ ## StableDiffusionLatentUpscalePipeline
16
+
17
+ The Stable Diffusion Latent Upscaler model was created by [Katherine Crowson](https://github.com/crowsonkb/k-diffusion) in collaboration with [Stability AI](https://stability.ai/). It can be used on top of any [`StableDiffusionUpscalePipeline`] checkpoint to enhance its output image resolution by a factor of 2.
18
+
19
+ A notebook that demonstrates the original implementation can be found here:
20
+ - [Stable Diffusion Upscaler Demo](https://colab.research.google.com/drive/1o1qYJcFeywzCIdkfKJy7cTpgZTCM2EI4)
21
+
22
+ Available Checkpoints are:
23
+ - *stabilityai/latent-upscaler*: [stabilityai/sd-x2-latent-upscaler](https://huggingface.co/stabilityai/sd-x2-latent-upscaler)
24
+
25
+
26
+ [[autodoc]] StableDiffusionLatentUpscalePipeline
27
+ - all
28
+ - __call__
29
+ - enable_sequential_cpu_offload
30
+ - enable_attention_slicing
31
+ - disable_attention_slicing
32
+ - enable_xformers_memory_efficient_attention
33
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/overview.mdx ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stable diffusion pipelines
14
+
15
+ Stable Diffusion is a text-to-image _latent diffusion_ model created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/) and [LAION](https://laion.ai/). It's trained on 512x512 images from a subset of the [LAION-5B](https://laion.ai/blog/laion-5b/) dataset. This model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts. With its 860M UNet and 123M text encoder, the model is relatively lightweight and can run on consumer GPUs.
16
+
17
+ Latent diffusion is the research on top of which Stable Diffusion was built. It was proposed in [High-Resolution Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) by Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, Björn Ommer. You can learn more details about it in the [specific pipeline for latent diffusion](pipelines/latent_diffusion) that is part of 🤗 Diffusers.
18
+
19
+ For more details about how Stable Diffusion works and how it differs from the base latent diffusion model, please refer to the official [launch announcement post](https://stability.ai/blog/stable-diffusion-announcement) and [this section of our own blog post](https://huggingface.co/blog/stable_diffusion#how-does-stable-diffusion-work).
20
+
21
+ *Tips*:
22
+ - To tweak your prompts on a specific result you liked, you can generate your own latents, as demonstrated in the following notebook: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pcuenca/diffusers-examples/blob/main/notebooks/stable-diffusion-seeds.ipynb)
23
+
24
+ *Overview*:
25
+
26
+ | Pipeline | Tasks | Colab | Demo
27
+ |---|---|:---:|:---:|
28
+ | [StableDiffusionPipeline](./text2img) | *Text-to-Image Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb) | [🤗 Stable Diffusion](https://huggingface.co/spaces/stabilityai/stable-diffusion)
29
+ | [StableDiffusionImg2ImgPipeline](./img2img) | *Image-to-Image Text-Guided Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/image_2_image_using_diffusers.ipynb) | [🤗 Diffuse the Rest](https://huggingface.co/spaces/huggingface/diffuse-the-rest)
30
+ | [StableDiffusionInpaintPipeline](./inpaint) | **Experimental** – *Text-Guided Image Inpainting* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/in_painting_with_stable_diffusion_using_diffusers.ipynb) | Coming soon
31
+ | [StableDiffusionDepth2ImgPipeline](./depth2img) | **Experimental** – *Depth-to-Image Text-Guided Generation * | | Coming soon
32
+ | [StableDiffusionImageVariationPipeline](./image_variation) | **Experimental** – *Image Variation Generation * | | [🤗 Stable Diffusion Image Variations](https://huggingface.co/spaces/lambdalabs/stable-diffusion-image-variations)
33
+ | [StableDiffusionUpscalePipeline](./upscale) | **Experimental** – *Text-Guided Image Super-Resolution * | | Coming soon
34
+ | [StableDiffusionLatentUpscalePipeline](./latent_upscale) | **Experimental** – *Text-Guided Image Super-Resolution * | | Coming soon
35
+ | [StableDiffusionInstructPix2PixPipeline](./pix2pix) | **Experimental** – *Text-Based Image Editing * | | [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://huggingface.co/spaces/timbrooks/instruct-pix2pix)
36
+
37
+
38
+
39
+ ## Tips
40
+
41
+ ### How to load and use different schedulers.
42
+
43
+ The stable diffusion pipeline uses [`PNDMScheduler`] scheduler by default. But `diffusers` provides many other schedulers that can be used with the stable diffusion pipeline such as [`DDIMScheduler`], [`LMSDiscreteScheduler`], [`EulerDiscreteScheduler`], [`EulerAncestralDiscreteScheduler`] etc.
44
+ To use a different scheduler, you can either change it via the [`ConfigMixin.from_config`] method or pass the `scheduler` argument to the `from_pretrained` method of the pipeline. For example, to use the [`EulerDiscreteScheduler`], you can do the following:
45
+
46
+ ```python
47
+ >>> from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
48
+
49
+ >>> pipeline = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
50
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
51
+
52
+ >>> # or
53
+ >>> euler_scheduler = EulerDiscreteScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")
54
+ >>> pipeline = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", scheduler=euler_scheduler)
55
+ ```
56
+
57
+
58
+ ### How to convert all use cases with multiple or single pipeline
59
+
60
+ If you want to use all possible use cases in a single `DiffusionPipeline` you can either:
61
+ - Make use of the [Stable Diffusion Mega Pipeline](https://github.com/huggingface/diffusers/tree/main/examples/community#stable-diffusion-mega) or
62
+ - Make use of the `components` functionality to instantiate all components in the most memory-efficient way:
63
+
64
+ ```python
65
+ >>> from diffusers import (
66
+ ... StableDiffusionPipeline,
67
+ ... StableDiffusionImg2ImgPipeline,
68
+ ... StableDiffusionInpaintPipeline,
69
+ ... )
70
+
71
+ >>> text2img = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
72
+ >>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
73
+ >>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
74
+
75
+ >>> # now you can use text2img(...), img2img(...), inpaint(...) just like the call methods of each respective pipeline
76
+ ```
77
+
78
+ ## StableDiffusionPipelineOutput
79
+ [[autodoc]] pipelines.stable_diffusion.StableDiffusionPipelineOutput
diffusers/docs/source/en/api/pipelines/stable_diffusion/pix2pix.mdx ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # InstructPix2Pix: Learning to Follow Image Editing Instructions
14
+
15
+ ## Overview
16
+
17
+ [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://arxiv.org/abs/2211.09800) by Tim Brooks, Aleksander Holynski and Alexei A. Efros.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ *We propose a method for editing images from human instructions: given an input image and a written instruction that tells the model what to do, our model follows these instructions to edit the image. To obtain training data for this problem, we combine the knowledge of two large pretrained models -- a language model (GPT-3) and a text-to-image model (Stable Diffusion) -- to generate a large dataset of image editing examples. Our conditional diffusion model, InstructPix2Pix, is trained on our generated data, and generalizes to real images and user-written instructions at inference time. Since it performs edits in the forward pass and does not require per example fine-tuning or inversion, our model edits images quickly, in a matter of seconds. We show compelling editing results for a diverse collection of input images and written instructions.*
22
+
23
+ Resources:
24
+
25
+ * [Project Page](https://www.timothybrooks.com/instruct-pix2pix).
26
+ * [Paper](https://arxiv.org/abs/2211.09800).
27
+ * [Original Code](https://github.com/timothybrooks/instruct-pix2pix).
28
+ * [Demo](https://huggingface.co/spaces/timbrooks/instruct-pix2pix).
29
+
30
+
31
+ ## Available Pipelines:
32
+
33
+ | Pipeline | Tasks | Demo
34
+ |---|---|:---:|
35
+ | [StableDiffusionInstructPix2PixPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py) | *Text-Based Image Editing* | [🤗 Space](https://huggingface.co/spaces/timbrooks/instruct-pix2pix) |
36
+
37
+ <!-- TODO: add Colab -->
38
+
39
+ ## Usage example
40
+
41
+ ```python
42
+ import PIL
43
+ import requests
44
+ import torch
45
+ from diffusers import StableDiffusionInstructPix2PixPipeline
46
+
47
+ model_id = "timbrooks/instruct-pix2pix"
48
+ pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
49
+
50
+ url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
51
+
52
+
53
+ def download_image(url):
54
+ image = PIL.Image.open(requests.get(url, stream=True).raw)
55
+ image = PIL.ImageOps.exif_transpose(image)
56
+ image = image.convert("RGB")
57
+ return image
58
+
59
+
60
+ image = download_image(url)
61
+
62
+ prompt = "make the mountains snowy"
63
+ edit = pipe(prompt, image=image, num_inference_steps=20, image_guidance_scale=1.5, guidance_scale=7).images[0]
64
+ images[0].save("snowy_mountains.png")
65
+ ```
66
+
67
+ ## StableDiffusionInstructPix2PixPipeline
68
+ [[autodoc]] StableDiffusionInstructPix2PixPipeline
69
+ - __call__
70
+ - all
diffusers/docs/source/en/api/pipelines/stable_diffusion/text2img.mdx ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Text-to-Image Generation
14
+
15
+ ## StableDiffusionPipeline
16
+
17
+ The Stable Diffusion model was created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), [runway](https://github.com/runwayml), and [LAION](https://laion.ai/). The [`StableDiffusionPipeline`] is capable of generating photo-realistic images given any text input using Stable Diffusion.
18
+
19
+ The original codebase can be found here:
20
+ - *Stable Diffusion V1*: [CampVis/stable-diffusion](https://github.com/CompVis/stable-diffusion)
21
+ - *Stable Diffusion v2*: [Stability-AI/stablediffusion](https://github.com/Stability-AI/stablediffusion)
22
+
23
+ Available Checkpoints are:
24
+ - *stable-diffusion-v1-4 (512x512 resolution)* [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4)
25
+ - *stable-diffusion-v1-5 (512x512 resolution)* [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5)
26
+ - *stable-diffusion-2-base (512x512 resolution)*: [stabilityai/stable-diffusion-2-base](https://huggingface.co/stabilityai/stable-diffusion-2-base)
27
+ - *stable-diffusion-2 (768x768 resolution)*: [stabilityai/stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2)
28
+ - *stable-diffusion-2-1-base (512x512 resolution)* [stabilityai/stable-diffusion-2-1-base](https://huggingface.co/stabilityai/stable-diffusion-2-1-base)
29
+ - *stable-diffusion-2-1 (768x768 resolution)*: [stabilityai/stable-diffusion-2-1](https://huggingface.co/stabilityai/stable-diffusion-2-1)
30
+
31
+ [[autodoc]] StableDiffusionPipeline
32
+ - all
33
+ - __call__
34
+ - enable_attention_slicing
35
+ - disable_attention_slicing
36
+ - enable_vae_slicing
37
+ - disable_vae_slicing
38
+ - enable_xformers_memory_efficient_attention
39
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion/upscale.mdx ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Super-Resolution
14
+
15
+ ## StableDiffusionUpscalePipeline
16
+
17
+ The upscaler diffusion model was created by the researchers and engineers from [CompVis](https://github.com/CompVis), [Stability AI](https://stability.ai/), and [LAION](https://laion.ai/), as part of Stable Diffusion 2.0. [`StableDiffusionUpscalePipeline`] can be used to enhance the resolution of input images by a factor of 4.
18
+
19
+ The original codebase can be found here:
20
+ - *Stable Diffusion v2*: [Stability-AI/stablediffusion](https://github.com/Stability-AI/stablediffusion#image-upscaling-with-stable-diffusion)
21
+
22
+ Available Checkpoints are:
23
+ - *stabilityai/stable-diffusion-x4-upscaler (x4 resolution resolution)*: [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)
24
+
25
+
26
+ [[autodoc]] StableDiffusionUpscalePipeline
27
+ - all
28
+ - __call__
29
+ - enable_attention_slicing
30
+ - disable_attention_slicing
31
+ - enable_xformers_memory_efficient_attention
32
+ - disable_xformers_memory_efficient_attention
diffusers/docs/source/en/api/pipelines/stable_diffusion_2.mdx ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stable diffusion 2
14
+
15
+ Stable Diffusion 2 is a text-to-image _latent diffusion_ model built upon the work of [Stable Diffusion 1](https://stability.ai/blog/stable-diffusion-public-release).
16
+ The project to train Stable Diffusion 2 was led by Robin Rombach and Katherine Crowson from [Stability AI](https://stability.ai/) and [LAION](https://laion.ai/).
17
+
18
+ *The Stable Diffusion 2.0 release includes robust text-to-image models trained using a brand new text encoder (OpenCLIP), developed by LAION with support from Stability AI, which greatly improves the quality of the generated images compared to earlier V1 releases. The text-to-image models in this release can generate images with default resolutions of both 512x512 pixels and 768x768 pixels.
19
+ These models are trained on an aesthetic subset of the [LAION-5B dataset](https://laion.ai/blog/laion-5b/) created by the DeepFloyd team at Stability AI, which is then further filtered to remove adult content using [LAION’s NSFW filter](https://openreview.net/forum?id=M3Y74vmsMcY).*
20
+
21
+ For more details about how Stable Diffusion 2 works and how it differs from Stable Diffusion 1, please refer to the official [launch announcement post](https://stability.ai/blog/stable-diffusion-v2-release).
22
+
23
+ ## Tips
24
+
25
+ ### Available checkpoints:
26
+
27
+ Note that the architecture is more or less identical to [Stable Diffusion 1](./stable_diffusion/overview) so please refer to [this page](./stable_diffusion/overview) for API documentation.
28
+
29
+ - *Text-to-Image (512x512 resolution)*: [stabilityai/stable-diffusion-2-base](https://huggingface.co/stabilityai/stable-diffusion-2-base) with [`StableDiffusionPipeline`]
30
+ - *Text-to-Image (768x768 resolution)*: [stabilityai/stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) with [`StableDiffusionPipeline`]
31
+ - *Image Inpainting (512x512 resolution)*: [stabilityai/stable-diffusion-2-inpainting](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting) with [`StableDiffusionInpaintPipeline`]
32
+ - *Super-Resolution (x4 resolution resolution)*: [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler) [`StableDiffusionUpscalePipeline`]
33
+ - *Depth-to-Image (512x512 resolution)*: [stabilityai/stable-diffusion-2-depth](https://huggingface.co/stabilityai/stable-diffusion-2-depth) with [`StableDiffusionDepth2ImagePipeline`]
34
+
35
+ We recommend using the [`DPMSolverMultistepScheduler`] as it's currently the fastest scheduler there is.
36
+
37
+
38
+ ### Text-to-Image
39
+
40
+ - *Text-to-Image (512x512 resolution)*: [stabilityai/stable-diffusion-2-base](https://huggingface.co/stabilityai/stable-diffusion-2-base) with [`StableDiffusionPipeline`]
41
+
42
+ ```python
43
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
44
+ import torch
45
+
46
+ repo_id = "stabilityai/stable-diffusion-2-base"
47
+ pipe = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.float16, revision="fp16")
48
+
49
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
50
+ pipe = pipe.to("cuda")
51
+
52
+ prompt = "High quality photo of an astronaut riding a horse in space"
53
+ image = pipe(prompt, num_inference_steps=25).images[0]
54
+ image.save("astronaut.png")
55
+ ```
56
+
57
+ - *Text-to-Image (768x768 resolution)*: [stabilityai/stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) with [`StableDiffusionPipeline`]
58
+
59
+ ```python
60
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
61
+ import torch
62
+
63
+ repo_id = "stabilityai/stable-diffusion-2"
64
+ pipe = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.float16, revision="fp16")
65
+
66
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
67
+ pipe = pipe.to("cuda")
68
+
69
+ prompt = "High quality photo of an astronaut riding a horse in space"
70
+ image = pipe(prompt, guidance_scale=9, num_inference_steps=25).images[0]
71
+ image.save("astronaut.png")
72
+ ```
73
+
74
+ ### Image Inpainting
75
+
76
+ - *Image Inpainting (512x512 resolution)*: [stabilityai/stable-diffusion-2-inpainting](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting) with [`StableDiffusionInpaintPipeline`]
77
+
78
+ ```python
79
+ import PIL
80
+ import requests
81
+ import torch
82
+ from io import BytesIO
83
+
84
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
85
+
86
+
87
+ def download_image(url):
88
+ response = requests.get(url)
89
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
90
+
91
+
92
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
93
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
94
+
95
+ init_image = download_image(img_url).resize((512, 512))
96
+ mask_image = download_image(mask_url).resize((512, 512))
97
+
98
+ repo_id = "stabilityai/stable-diffusion-2-inpainting"
99
+ pipe = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.float16, revision="fp16")
100
+
101
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
102
+ pipe = pipe.to("cuda")
103
+
104
+ prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
105
+ image = pipe(prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=25).images[0]
106
+
107
+ image.save("yellow_cat.png")
108
+ ```
109
+
110
+ ### Super-Resolution
111
+
112
+ - *Image Upscaling (x4 resolution resolution)*: [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler) with [`StableDiffusionUpscalePipeline`]
113
+
114
+
115
+ ```python
116
+ import requests
117
+ from PIL import Image
118
+ from io import BytesIO
119
+ from diffusers import StableDiffusionUpscalePipeline
120
+ import torch
121
+
122
+ # load model and scheduler
123
+ model_id = "stabilityai/stable-diffusion-x4-upscaler"
124
+ pipeline = StableDiffusionUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
125
+ pipeline = pipeline.to("cuda")
126
+
127
+ # let's download an image
128
+ url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
129
+ response = requests.get(url)
130
+ low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
131
+ low_res_img = low_res_img.resize((128, 128))
132
+ prompt = "a white cat"
133
+ upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
134
+ upscaled_image.save("upsampled_cat.png")
135
+ ```
136
+
137
+ ### Depth-to-Image
138
+
139
+ - *Depth-Guided Text-to-Image*: [stabilityai/stable-diffusion-2-depth](https://huggingface.co/stabilityai/stable-diffusion-2-depth) [`StableDiffusionDepth2ImagePipeline`]
140
+
141
+
142
+ ```python
143
+ import torch
144
+ import requests
145
+ from PIL import Image
146
+
147
+ from diffusers import StableDiffusionDepth2ImgPipeline
148
+
149
+ pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(
150
+ "stabilityai/stable-diffusion-2-depth",
151
+ torch_dtype=torch.float16,
152
+ ).to("cuda")
153
+
154
+
155
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
156
+ init_image = Image.open(requests.get(url, stream=True).raw)
157
+ prompt = "two tigers"
158
+ n_propmt = "bad, deformed, ugly, bad anotomy"
159
+ image = pipe(prompt=prompt, image=init_image, negative_prompt=n_propmt, strength=0.7).images[0]
160
+ ```
161
+
162
+ ### How to load and use different schedulers.
163
+
164
+ The stable diffusion pipeline uses [`DDIMScheduler`] scheduler by default. But `diffusers` provides many other schedulers that can be used with the stable diffusion pipeline such as [`PNDMScheduler`], [`LMSDiscreteScheduler`], [`EulerDiscreteScheduler`], [`EulerAncestralDiscreteScheduler`] etc.
165
+ To use a different scheduler, you can either change it via the [`ConfigMixin.from_config`] method or pass the `scheduler` argument to the `from_pretrained` method of the pipeline. For example, to use the [`EulerDiscreteScheduler`], you can do the following:
166
+
167
+ ```python
168
+ >>> from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
169
+
170
+ >>> pipeline = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2")
171
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
172
+
173
+ >>> # or
174
+ >>> euler_scheduler = EulerDiscreteScheduler.from_pretrained("stabilityai/stable-diffusion-2", subfolder="scheduler")
175
+ >>> pipeline = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", scheduler=euler_scheduler)
176
+ ```
diffusers/docs/source/en/api/pipelines/stable_diffusion_safe.mdx ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Safe Stable Diffusion
14
+
15
+ Safe Stable Diffusion was proposed in [Safe Latent Diffusion: Mitigating Inappropriate Degeneration in Diffusion Models](https://arxiv.org/abs/2211.05105) and mitigates the well known issue that models like Stable Diffusion that are trained on unfiltered, web-crawled datasets tend to suffer from inappropriate degeneration. For instance Stable Diffusion may unexpectedly generate nudity, violence, images depicting self-harm, or otherwise offensive content.
16
+ Safe Stable Diffusion is an extension to the Stable Diffusion that drastically reduces content like this.
17
+
18
+ The abstract of the paper is the following:
19
+
20
+ *Text-conditioned image generation models have recently achieved astonishing results in image quality and text alignment and are consequently employed in a fast-growing number of applications. Since they are highly data-driven, relying on billion-sized datasets randomly scraped from the internet, they also suffer, as we demonstrate, from degenerated and biased human behavior. In turn, they may even reinforce such biases. To help combat these undesired side effects, we present safe latent diffusion (SLD). Specifically, to measure the inappropriate degeneration due to unfiltered and imbalanced training sets, we establish a novel image generation test bed-inappropriate image prompts (I2P)-containing dedicated, real-world image-to-text prompts covering concepts such as nudity and violence. As our exhaustive empirical evaluation demonstrates, the introduced SLD removes and suppresses inappropriate image parts during the diffusion process, with no additional training required and no adverse effect on overall image quality or text alignment.*
21
+
22
+
23
+ *Overview*:
24
+
25
+ | Pipeline | Tasks | Colab | Demo
26
+ |---|---|:---:|:---:|
27
+ | [pipeline_stable_diffusion_safe.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py) | *Text-to-Image Generation* | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ml-research/safe-latent-diffusion/blob/main/examples/Safe%20Latent%20Diffusion.ipynb) | -
28
+
29
+ ## Tips
30
+
31
+ - Safe Stable Diffusion may also be used with weights of [Stable Diffusion](./api/pipelines/stable_diffusion/text2img).
32
+
33
+ ### Run Safe Stable Diffusion
34
+
35
+ Safe Stable Diffusion can be tested very easily with the [`StableDiffusionPipelineSafe`], and the `"AIML-TUDA/stable-diffusion-safe"` checkpoint exactly in the same way it is shown in the [Conditional Image Generation Guide](./using-diffusers/conditional_image_generation).
36
+
37
+ ### Interacting with the Safety Concept
38
+
39
+ To check and edit the currently used safety concept, use the `safety_concept` property of [`StableDiffusionPipelineSafe`]
40
+ ```python
41
+ >>> from diffusers import StableDiffusionPipelineSafe
42
+
43
+ >>> pipeline = StableDiffusionPipelineSafe.from_pretrained("AIML-TUDA/stable-diffusion-safe")
44
+ >>> pipeline.safety_concept
45
+ ```
46
+ For each image generation the active concept is also contained in [`StableDiffusionSafePipelineOutput`].
47
+
48
+ ### Using pre-defined safety configurations
49
+
50
+ You may use the 4 configurations defined in the [Safe Latent Diffusion paper](https://arxiv.org/abs/2211.05105) as follows:
51
+
52
+ ```python
53
+ >>> from diffusers import StableDiffusionPipelineSafe
54
+ >>> from diffusers.pipelines.stable_diffusion_safe import SafetyConfig
55
+
56
+ >>> pipeline = StableDiffusionPipelineSafe.from_pretrained("AIML-TUDA/stable-diffusion-safe")
57
+ >>> prompt = "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c. leyendecker"
58
+ >>> out = pipeline(prompt=prompt, **SafetyConfig.MAX)
59
+ ```
60
+
61
+ The following configurations are available: `SafetyConfig.WEAK`, `SafetyConfig.MEDIUM`, `SafetyConfig.STRONg`, and `SafetyConfig.MAX`.
62
+
63
+ ### How to load and use different schedulers.
64
+
65
+ The safe stable diffusion pipeline uses [`PNDMScheduler`] scheduler by default. But `diffusers` provides many other schedulers that can be used with the stable diffusion pipeline such as [`DDIMScheduler`], [`LMSDiscreteScheduler`], [`EulerDiscreteScheduler`], [`EulerAncestralDiscreteScheduler`] etc.
66
+ To use a different scheduler, you can either change it via the [`ConfigMixin.from_config`] method or pass the `scheduler` argument to the `from_pretrained` method of the pipeline. For example, to use the [`EulerDiscreteScheduler`], you can do the following:
67
+
68
+ ```python
69
+ >>> from diffusers import StableDiffusionPipelineSafe, EulerDiscreteScheduler
70
+
71
+ >>> pipeline = StableDiffusionPipelineSafe.from_pretrained("AIML-TUDA/stable-diffusion-safe")
72
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
73
+
74
+ >>> # or
75
+ >>> euler_scheduler = EulerDiscreteScheduler.from_pretrained("AIML-TUDA/stable-diffusion-safe", subfolder="scheduler")
76
+ >>> pipeline = StableDiffusionPipelineSafe.from_pretrained(
77
+ ... "AIML-TUDA/stable-diffusion-safe", scheduler=euler_scheduler
78
+ ... )
79
+ ```
80
+
81
+
82
+ ## StableDiffusionSafePipelineOutput
83
+ [[autodoc]] pipelines.stable_diffusion_safe.StableDiffusionSafePipelineOutput
84
+ - all
85
+ - __call__
86
+
87
+ ## StableDiffusionPipelineSafe
88
+ [[autodoc]] StableDiffusionPipelineSafe
89
+ - all
90
+ - __call__
diffusers/docs/source/en/api/pipelines/stochastic_karras_ve.mdx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stochastic Karras VE
14
+
15
+ ## Overview
16
+
17
+ [Elucidating the Design Space of Diffusion-Based Generative Models](https://arxiv.org/abs/2206.00364) by Tero Karras, Miika Aittala, Timo Aila and Samuli Laine.
18
+
19
+ The abstract of the paper is the following:
20
+
21
+ We argue that the theory and practice of diffusion-based generative models are currently unnecessarily convoluted and seek to remedy the situation by presenting a design space that clearly separates the concrete design choices. This lets us identify several changes to both the sampling and training processes, as well as preconditioning of the score networks. Together, our improvements yield new state-of-the-art FID of 1.79 for CIFAR-10 in a class-conditional setting and 1.97 in an unconditional setting, with much faster sampling (35 network evaluations per image) than prior designs. To further demonstrate their modular nature, we show that our design changes dramatically improve both the efficiency and quality obtainable with pre-trained score networks from previous work, including improving the FID of an existing ImageNet-64 model from 2.07 to near-SOTA 1.55.
22
+
23
+ This pipeline implements the Stochastic sampling tailored to the Variance-Expanding (VE) models.
24
+
25
+
26
+ ## Available Pipelines:
27
+
28
+ | Pipeline | Tasks | Colab
29
+ |---|---|:---:|
30
+ | [pipeline_stochastic_karras_ve.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stochastic_karras_ve/pipeline_stochastic_karras_ve.py) | *Unconditional Image Generation* | - |
31
+
32
+
33
+ ## KarrasVePipeline
34
+ [[autodoc]] KarrasVePipeline
35
+ - all
36
+ - __call__