Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .eslintignore +4 -0
- .eslintrc.js +98 -0
- .git-blame-ignore-revs +2 -0
- .github/ISSUE_TEMPLATE/bug_report.yml +105 -0
- .github/ISSUE_TEMPLATE/config.yml +5 -0
- .github/ISSUE_TEMPLATE/feature_request.yml +40 -0
- .github/pull_request_template.md +15 -0
- .github/workflows/on_pull_request.yaml +38 -0
- .github/workflows/run_tests.yaml +81 -0
- .github/workflows/warns_merge_master.yml +19 -0
- .gitignore +44 -0
- .pylintrc +3 -0
- CHANGELOG.md +1085 -0
- CITATION.cff +7 -0
- CODEOWNERS +12 -0
- LICENSE.txt +663 -0
- README.md +211 -12
- _typos.toml +5 -0
- configs/alt-diffusion-inference.yaml +72 -0
- configs/alt-diffusion-m18-inference.yaml +73 -0
- configs/instruct-pix2pix.yaml +98 -0
- configs/sd3-inference.yaml +5 -0
- configs/sd_xl_inpaint.yaml +98 -0
- configs/v1-inference.yaml +70 -0
- configs/v1-inpainting-inference.yaml +70 -0
- environment-wsl2.yaml +11 -0
- extensions-builtin/LDSR/ldsr_model_arch.py +250 -0
- extensions-builtin/LDSR/preload.py +6 -0
- extensions-builtin/LDSR/scripts/ldsr_model.py +68 -0
- extensions-builtin/LDSR/sd_hijack_autoencoder.py +293 -0
- extensions-builtin/LDSR/sd_hijack_ddpm_v1.py +1443 -0
- extensions-builtin/LDSR/vqvae_quantize.py +147 -0
- extensions-builtin/Lora/extra_networks_lora.py +62 -0
- extensions-builtin/Lora/lora.py +9 -0
- extensions-builtin/Lora/lora_logger.py +33 -0
- extensions-builtin/Lora/lora_patches.py +31 -0
- extensions-builtin/Lora/lyco_helpers.py +68 -0
- extensions-builtin/Lora/network.py +228 -0
- extensions-builtin/Lora/network_full.py +27 -0
- extensions-builtin/Lora/network_glora.py +33 -0
- extensions-builtin/Lora/network_hada.py +55 -0
- extensions-builtin/Lora/network_ia3.py +30 -0
- extensions-builtin/Lora/network_lokr.py +64 -0
- extensions-builtin/Lora/network_lora.py +94 -0
- extensions-builtin/Lora/network_norm.py +28 -0
- extensions-builtin/Lora/network_oft.py +118 -0
- extensions-builtin/Lora/networks.py +737 -0
- extensions-builtin/Lora/preload.py +8 -0
- extensions-builtin/Lora/scripts/lora_script.py +102 -0
- extensions-builtin/Lora/ui_edit_user_metadata.py +226 -0
.eslintignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extensions
|
2 |
+
extensions-disabled
|
3 |
+
repositories
|
4 |
+
venv
|
.eslintrc.js
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* global module */
|
2 |
+
module.exports = {
|
3 |
+
env: {
|
4 |
+
browser: true,
|
5 |
+
es2021: true,
|
6 |
+
},
|
7 |
+
extends: "eslint:recommended",
|
8 |
+
parserOptions: {
|
9 |
+
ecmaVersion: "latest",
|
10 |
+
},
|
11 |
+
rules: {
|
12 |
+
"arrow-spacing": "error",
|
13 |
+
"block-spacing": "error",
|
14 |
+
"brace-style": "error",
|
15 |
+
"comma-dangle": ["error", "only-multiline"],
|
16 |
+
"comma-spacing": "error",
|
17 |
+
"comma-style": ["error", "last"],
|
18 |
+
"curly": ["error", "multi-line", "consistent"],
|
19 |
+
"eol-last": "error",
|
20 |
+
"func-call-spacing": "error",
|
21 |
+
"function-call-argument-newline": ["error", "consistent"],
|
22 |
+
"function-paren-newline": ["error", "consistent"],
|
23 |
+
"indent": ["error", 4],
|
24 |
+
"key-spacing": "error",
|
25 |
+
"keyword-spacing": "error",
|
26 |
+
"linebreak-style": ["error", "unix"],
|
27 |
+
"no-extra-semi": "error",
|
28 |
+
"no-mixed-spaces-and-tabs": "error",
|
29 |
+
"no-multi-spaces": "error",
|
30 |
+
"no-redeclare": ["error", {builtinGlobals: false}],
|
31 |
+
"no-trailing-spaces": "error",
|
32 |
+
"no-unused-vars": "off",
|
33 |
+
"no-whitespace-before-property": "error",
|
34 |
+
"object-curly-newline": ["error", {consistent: true, multiline: true}],
|
35 |
+
"object-curly-spacing": ["error", "never"],
|
36 |
+
"operator-linebreak": ["error", "after"],
|
37 |
+
"quote-props": ["error", "consistent-as-needed"],
|
38 |
+
"semi": ["error", "always"],
|
39 |
+
"semi-spacing": "error",
|
40 |
+
"semi-style": ["error", "last"],
|
41 |
+
"space-before-blocks": "error",
|
42 |
+
"space-before-function-paren": ["error", "never"],
|
43 |
+
"space-in-parens": ["error", "never"],
|
44 |
+
"space-infix-ops": "error",
|
45 |
+
"space-unary-ops": "error",
|
46 |
+
"switch-colon-spacing": "error",
|
47 |
+
"template-curly-spacing": ["error", "never"],
|
48 |
+
"unicode-bom": "error",
|
49 |
+
},
|
50 |
+
globals: {
|
51 |
+
//script.js
|
52 |
+
gradioApp: "readonly",
|
53 |
+
executeCallbacks: "readonly",
|
54 |
+
onAfterUiUpdate: "readonly",
|
55 |
+
onOptionsChanged: "readonly",
|
56 |
+
onUiLoaded: "readonly",
|
57 |
+
onUiUpdate: "readonly",
|
58 |
+
uiCurrentTab: "writable",
|
59 |
+
uiElementInSight: "readonly",
|
60 |
+
uiElementIsVisible: "readonly",
|
61 |
+
//ui.js
|
62 |
+
opts: "writable",
|
63 |
+
all_gallery_buttons: "readonly",
|
64 |
+
selected_gallery_button: "readonly",
|
65 |
+
selected_gallery_index: "readonly",
|
66 |
+
switch_to_txt2img: "readonly",
|
67 |
+
switch_to_img2img_tab: "readonly",
|
68 |
+
switch_to_img2img: "readonly",
|
69 |
+
switch_to_sketch: "readonly",
|
70 |
+
switch_to_inpaint: "readonly",
|
71 |
+
switch_to_inpaint_sketch: "readonly",
|
72 |
+
switch_to_extras: "readonly",
|
73 |
+
get_tab_index: "readonly",
|
74 |
+
create_submit_args: "readonly",
|
75 |
+
restart_reload: "readonly",
|
76 |
+
updateInput: "readonly",
|
77 |
+
onEdit: "readonly",
|
78 |
+
//extraNetworks.js
|
79 |
+
requestGet: "readonly",
|
80 |
+
popup: "readonly",
|
81 |
+
// profilerVisualization.js
|
82 |
+
createVisualizationTable: "readonly",
|
83 |
+
// from python
|
84 |
+
localization: "readonly",
|
85 |
+
// progrssbar.js
|
86 |
+
randomId: "readonly",
|
87 |
+
requestProgress: "readonly",
|
88 |
+
// imageviewer.js
|
89 |
+
modalPrevImage: "readonly",
|
90 |
+
modalNextImage: "readonly",
|
91 |
+
// localStorage.js
|
92 |
+
localSet: "readonly",
|
93 |
+
localGet: "readonly",
|
94 |
+
localRemove: "readonly",
|
95 |
+
// resizeHandle.js
|
96 |
+
setupResizeHandle: "writable"
|
97 |
+
}
|
98 |
+
};
|
.git-blame-ignore-revs
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# Apply ESlint
|
2 |
+
9c54b78d9dde5601e916f308d9a9d6953ec39430
|
.github/ISSUE_TEMPLATE/bug_report.yml
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Bug Report
|
2 |
+
description: You think something is broken in the UI
|
3 |
+
title: "[Bug]: "
|
4 |
+
labels: ["bug-report"]
|
5 |
+
|
6 |
+
body:
|
7 |
+
- type: markdown
|
8 |
+
attributes:
|
9 |
+
value: |
|
10 |
+
> The title of the bug report should be short and descriptive.
|
11 |
+
> Use relevant keywords for searchability.
|
12 |
+
> Do not leave it blank, but also do not put an entire error log in it.
|
13 |
+
- type: checkboxes
|
14 |
+
attributes:
|
15 |
+
label: Checklist
|
16 |
+
description: |
|
17 |
+
Please perform basic debugging to see if extensions or configuration is the cause of the issue.
|
18 |
+
Basic debug procedure
|
19 |
+
1. Disable all third-party extensions - check if extension is the cause
|
20 |
+
2. Update extensions and webui - sometimes things just need to be updated
|
21 |
+
3. Backup and remove your config.json and ui-config.json - check if the issue is caused by bad configuration
|
22 |
+
4. Delete venv with third-party extensions disabled - sometimes extensions might cause wrong libraries to be installed
|
23 |
+
5. Try a fresh installation webui in a different directory - see if a clean installation solves the issue
|
24 |
+
Before making a issue report please, check that the issue hasn't been reported recently.
|
25 |
+
options:
|
26 |
+
- label: The issue exists after disabling all extensions
|
27 |
+
- label: The issue exists on a clean installation of webui
|
28 |
+
- label: The issue is caused by an extension, but I believe it is caused by a bug in the webui
|
29 |
+
- label: The issue exists in the current version of the webui
|
30 |
+
- label: The issue has not been reported before recently
|
31 |
+
- label: The issue has been reported before but has not been fixed yet
|
32 |
+
- type: markdown
|
33 |
+
attributes:
|
34 |
+
value: |
|
35 |
+
> Please fill this form with as much information as possible. Don't forget to "Upload Sysinfo" and "What browsers" and provide screenshots if possible
|
36 |
+
- type: textarea
|
37 |
+
id: what-did
|
38 |
+
attributes:
|
39 |
+
label: What happened?
|
40 |
+
description: Tell us what happened in a very clear and simple way
|
41 |
+
placeholder: |
|
42 |
+
txt2img is not working as intended.
|
43 |
+
validations:
|
44 |
+
required: true
|
45 |
+
- type: textarea
|
46 |
+
id: steps
|
47 |
+
attributes:
|
48 |
+
label: Steps to reproduce the problem
|
49 |
+
description: Please provide us with precise step by step instructions on how to reproduce the bug
|
50 |
+
placeholder: |
|
51 |
+
1. Go to ...
|
52 |
+
2. Press ...
|
53 |
+
3. ...
|
54 |
+
validations:
|
55 |
+
required: true
|
56 |
+
- type: textarea
|
57 |
+
id: what-should
|
58 |
+
attributes:
|
59 |
+
label: What should have happened?
|
60 |
+
description: Tell us what you think the normal behavior should be
|
61 |
+
placeholder: |
|
62 |
+
WebUI should ...
|
63 |
+
validations:
|
64 |
+
required: true
|
65 |
+
- type: dropdown
|
66 |
+
id: browsers
|
67 |
+
attributes:
|
68 |
+
label: What browsers do you use to access the UI ?
|
69 |
+
multiple: true
|
70 |
+
options:
|
71 |
+
- Mozilla Firefox
|
72 |
+
- Google Chrome
|
73 |
+
- Brave
|
74 |
+
- Apple Safari
|
75 |
+
- Microsoft Edge
|
76 |
+
- Android
|
77 |
+
- iOS
|
78 |
+
- Other
|
79 |
+
- type: textarea
|
80 |
+
id: sysinfo
|
81 |
+
attributes:
|
82 |
+
label: Sysinfo
|
83 |
+
description: System info file, generated by WebUI. You can generate it in settings, on the Sysinfo page. Drag the file into the field to upload it. If you submit your report without including the sysinfo file, the report will be closed. If needed, review the report to make sure it includes no personal information you don't want to share. If you can't start WebUI, you can use --dump-sysinfo commandline argument to generate the file.
|
84 |
+
placeholder: |
|
85 |
+
1. Go to WebUI Settings -> Sysinfo -> Download system info.
|
86 |
+
If WebUI fails to launch, use --dump-sysinfo commandline argument to generate the file
|
87 |
+
2. Upload the Sysinfo as a attached file, Do NOT paste it in as plain text.
|
88 |
+
validations:
|
89 |
+
required: true
|
90 |
+
- type: textarea
|
91 |
+
id: logs
|
92 |
+
attributes:
|
93 |
+
label: Console logs
|
94 |
+
description: Please provide **full** cmd/terminal logs from the moment you started UI to the end of it, after the bug occurred. If it's very long, provide a link to pastebin or similar service.
|
95 |
+
render: Shell
|
96 |
+
validations:
|
97 |
+
required: true
|
98 |
+
- type: textarea
|
99 |
+
id: misc
|
100 |
+
attributes:
|
101 |
+
label: Additional information
|
102 |
+
description: |
|
103 |
+
Please provide us with any relevant additional info or context.
|
104 |
+
Examples:
|
105 |
+
I have updated my GPU driver recently.
|
.github/ISSUE_TEMPLATE/config.yml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
blank_issues_enabled: false
|
2 |
+
contact_links:
|
3 |
+
- name: WebUI Community Support
|
4 |
+
url: https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions
|
5 |
+
about: Please ask and answer questions here.
|
.github/ISSUE_TEMPLATE/feature_request.yml
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Feature request
|
2 |
+
description: Suggest an idea for this project
|
3 |
+
title: "[Feature Request]: "
|
4 |
+
labels: ["enhancement"]
|
5 |
+
|
6 |
+
body:
|
7 |
+
- type: checkboxes
|
8 |
+
attributes:
|
9 |
+
label: Is there an existing issue for this?
|
10 |
+
description: Please search to see if an issue already exists for the feature you want, and that it's not implemented in a recent build/commit.
|
11 |
+
options:
|
12 |
+
- label: I have searched the existing issues and checked the recent builds/commits
|
13 |
+
required: true
|
14 |
+
- type: markdown
|
15 |
+
attributes:
|
16 |
+
value: |
|
17 |
+
*Please fill this form with as much information as possible, provide screenshots and/or illustrations of the feature if possible*
|
18 |
+
- type: textarea
|
19 |
+
id: feature
|
20 |
+
attributes:
|
21 |
+
label: What would your feature do ?
|
22 |
+
description: Tell us about your feature in a very clear and simple way, and what problem it would solve
|
23 |
+
validations:
|
24 |
+
required: true
|
25 |
+
- type: textarea
|
26 |
+
id: workflow
|
27 |
+
attributes:
|
28 |
+
label: Proposed workflow
|
29 |
+
description: Please provide us with step by step information on how you'd like the feature to be accessed and used
|
30 |
+
value: |
|
31 |
+
1. Go to ....
|
32 |
+
2. Press ....
|
33 |
+
3. ...
|
34 |
+
validations:
|
35 |
+
required: true
|
36 |
+
- type: textarea
|
37 |
+
id: misc
|
38 |
+
attributes:
|
39 |
+
label: Additional information
|
40 |
+
description: Add any other context or screenshots about the feature request here.
|
.github/pull_request_template.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Description
|
2 |
+
|
3 |
+
* a simple description of what you're trying to accomplish
|
4 |
+
* a summary of changes in code
|
5 |
+
* which issues it fixes, if any
|
6 |
+
|
7 |
+
## Screenshots/videos:
|
8 |
+
|
9 |
+
|
10 |
+
## Checklist:
|
11 |
+
|
12 |
+
- [ ] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
13 |
+
- [ ] I have performed a self-review of my own code
|
14 |
+
- [ ] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style)
|
15 |
+
- [ ] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
|
.github/workflows/on_pull_request.yaml
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Linter
|
2 |
+
|
3 |
+
on:
|
4 |
+
- push
|
5 |
+
- pull_request
|
6 |
+
|
7 |
+
jobs:
|
8 |
+
lint-python:
|
9 |
+
name: ruff
|
10 |
+
runs-on: ubuntu-latest
|
11 |
+
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
12 |
+
steps:
|
13 |
+
- name: Checkout Code
|
14 |
+
uses: actions/checkout@v4
|
15 |
+
- uses: actions/setup-python@v5
|
16 |
+
with:
|
17 |
+
python-version: 3.11
|
18 |
+
# NB: there's no cache: pip here since we're not installing anything
|
19 |
+
# from the requirements.txt file(s) in the repository; it's faster
|
20 |
+
# not to have GHA download an (at the time of writing) 4 GB cache
|
21 |
+
# of PyTorch and other dependencies.
|
22 |
+
- name: Install Ruff
|
23 |
+
run: pip install ruff==0.3.3
|
24 |
+
- name: Run Ruff
|
25 |
+
run: ruff .
|
26 |
+
lint-js:
|
27 |
+
name: eslint
|
28 |
+
runs-on: ubuntu-latest
|
29 |
+
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
30 |
+
steps:
|
31 |
+
- name: Checkout Code
|
32 |
+
uses: actions/checkout@v4
|
33 |
+
- name: Install Node.js
|
34 |
+
uses: actions/setup-node@v4
|
35 |
+
with:
|
36 |
+
node-version: 18
|
37 |
+
- run: npm i --ci
|
38 |
+
- run: npm run lint
|
.github/workflows/run_tests.yaml
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Tests
|
2 |
+
|
3 |
+
on:
|
4 |
+
- push
|
5 |
+
- pull_request
|
6 |
+
|
7 |
+
jobs:
|
8 |
+
test:
|
9 |
+
name: tests on CPU with empty model
|
10 |
+
runs-on: ubuntu-latest
|
11 |
+
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
12 |
+
steps:
|
13 |
+
- name: Checkout Code
|
14 |
+
uses: actions/checkout@v4
|
15 |
+
- name: Set up Python 3.10
|
16 |
+
uses: actions/setup-python@v5
|
17 |
+
with:
|
18 |
+
python-version: 3.10.6
|
19 |
+
cache: pip
|
20 |
+
cache-dependency-path: |
|
21 |
+
**/requirements*txt
|
22 |
+
launch.py
|
23 |
+
- name: Cache models
|
24 |
+
id: cache-models
|
25 |
+
uses: actions/cache@v4
|
26 |
+
with:
|
27 |
+
path: models
|
28 |
+
key: "2023-12-30"
|
29 |
+
- name: Install test dependencies
|
30 |
+
run: pip install wait-for-it -r requirements-test.txt
|
31 |
+
env:
|
32 |
+
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
33 |
+
PIP_PROGRESS_BAR: "off"
|
34 |
+
- name: Setup environment
|
35 |
+
run: python launch.py --skip-torch-cuda-test --exit
|
36 |
+
env:
|
37 |
+
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
38 |
+
PIP_PROGRESS_BAR: "off"
|
39 |
+
TORCH_INDEX_URL: https://download.pytorch.org/whl/cpu
|
40 |
+
WEBUI_LAUNCH_LIVE_OUTPUT: "1"
|
41 |
+
PYTHONUNBUFFERED: "1"
|
42 |
+
- name: Print installed packages
|
43 |
+
run: pip freeze
|
44 |
+
- name: Start test server
|
45 |
+
run: >
|
46 |
+
python -m coverage run
|
47 |
+
--data-file=.coverage.server
|
48 |
+
launch.py
|
49 |
+
--skip-prepare-environment
|
50 |
+
--skip-torch-cuda-test
|
51 |
+
--test-server
|
52 |
+
--do-not-download-clip
|
53 |
+
--no-half
|
54 |
+
--disable-opt-split-attention
|
55 |
+
--use-cpu all
|
56 |
+
--api-server-stop
|
57 |
+
2>&1 | tee output.txt &
|
58 |
+
- name: Run tests
|
59 |
+
run: |
|
60 |
+
wait-for-it --service 127.0.0.1:7860 -t 20
|
61 |
+
python -m pytest -vv --junitxml=test/results.xml --cov . --cov-report=xml --verify-base-url test
|
62 |
+
- name: Kill test server
|
63 |
+
if: always()
|
64 |
+
run: curl -vv -XPOST http://127.0.0.1:7860/sdapi/v1/server-stop && sleep 10
|
65 |
+
- name: Show coverage
|
66 |
+
run: |
|
67 |
+
python -m coverage combine .coverage*
|
68 |
+
python -m coverage report -i
|
69 |
+
python -m coverage html -i
|
70 |
+
- name: Upload main app output
|
71 |
+
uses: actions/upload-artifact@v4
|
72 |
+
if: always()
|
73 |
+
with:
|
74 |
+
name: output
|
75 |
+
path: output.txt
|
76 |
+
- name: Upload coverage HTML
|
77 |
+
uses: actions/upload-artifact@v4
|
78 |
+
if: always()
|
79 |
+
with:
|
80 |
+
name: htmlcov
|
81 |
+
path: htmlcov
|
.github/workflows/warns_merge_master.yml
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Pull requests can't target master branch
|
2 |
+
|
3 |
+
"on":
|
4 |
+
pull_request:
|
5 |
+
types:
|
6 |
+
- opened
|
7 |
+
- synchronize
|
8 |
+
- reopened
|
9 |
+
branches:
|
10 |
+
- master
|
11 |
+
|
12 |
+
jobs:
|
13 |
+
check:
|
14 |
+
runs-on: ubuntu-latest
|
15 |
+
steps:
|
16 |
+
- name: Warning marge into master
|
17 |
+
run: |
|
18 |
+
echo -e "::warning::This pull request directly merge into \"master\" branch, normally development happens on \"dev\" branch."
|
19 |
+
exit 1
|
.gitignore
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__
|
2 |
+
*.ckpt
|
3 |
+
*.safetensors
|
4 |
+
*.pth
|
5 |
+
.DS_Store
|
6 |
+
/ESRGAN/*
|
7 |
+
/SwinIR/*
|
8 |
+
/repositories
|
9 |
+
/venv
|
10 |
+
/tmp
|
11 |
+
/model.ckpt
|
12 |
+
/models/**/*
|
13 |
+
/GFPGANv1.3.pth
|
14 |
+
/gfpgan/weights/*.pth
|
15 |
+
/ui-config.json
|
16 |
+
/outputs
|
17 |
+
/config.json
|
18 |
+
/log
|
19 |
+
/webui.settings.bat
|
20 |
+
/embeddings
|
21 |
+
/styles.csv
|
22 |
+
/params.txt
|
23 |
+
/styles.csv.bak
|
24 |
+
/webui-user.bat
|
25 |
+
/webui-user.sh
|
26 |
+
/interrogate
|
27 |
+
/user.css
|
28 |
+
/.idea
|
29 |
+
notification.mp3
|
30 |
+
/SwinIR
|
31 |
+
/textual_inversion
|
32 |
+
.vscode
|
33 |
+
/extensions
|
34 |
+
/test/stdout.txt
|
35 |
+
/test/stderr.txt
|
36 |
+
/cache.json*
|
37 |
+
/config_states/
|
38 |
+
/node_modules
|
39 |
+
/package-lock.json
|
40 |
+
/.coverage*
|
41 |
+
/test/test_outputs
|
42 |
+
/cache
|
43 |
+
trace.json
|
44 |
+
/sysinfo-????-??-??-??-??.json
|
.pylintrc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# See https://pylint.pycqa.org/en/latest/user_guide/messages/message_control.html
|
2 |
+
[MESSAGES CONTROL]
|
3 |
+
disable=C,R,W,E,I
|
CHANGELOG.md
ADDED
@@ -0,0 +1,1085 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## 1.10.1
|
2 |
+
|
3 |
+
### Bug Fixes:
|
4 |
+
* fix image upscale on cpu ([#16275](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16275))
|
5 |
+
|
6 |
+
|
7 |
+
## 1.10.0
|
8 |
+
|
9 |
+
### Features:
|
10 |
+
* A lot of performance improvements (see below in Performance section)
|
11 |
+
* Stable Diffusion 3 support ([#16030](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16030), [#16164](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16164), [#16212](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16212))
|
12 |
+
* Recommended Euler sampler; DDIM and other timestamp samplers currently not supported
|
13 |
+
* T5 text model is disabled by default, enable it in settings
|
14 |
+
* New schedulers:
|
15 |
+
* Align Your Steps ([#15751](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15751))
|
16 |
+
* KL Optimal ([#15608](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15608))
|
17 |
+
* Normal ([#16149](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16149))
|
18 |
+
* DDIM ([#16149](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16149))
|
19 |
+
* Simple ([#16142](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16142))
|
20 |
+
* Beta ([#16235](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16235))
|
21 |
+
* New sampler: DDIM CFG++ ([#16035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16035))
|
22 |
+
|
23 |
+
### Minor:
|
24 |
+
* Option to skip CFG on early steps ([#15607](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15607))
|
25 |
+
* Add --models-dir option ([#15742](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15742))
|
26 |
+
* Allow mobile users to open context menu by using two fingers press ([#15682](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15682))
|
27 |
+
* Infotext: add Lora name as TI hashes for bundled Textual Inversion ([#15679](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15679))
|
28 |
+
* Check model's hash after downloading it to prevent corruped downloads ([#15602](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15602))
|
29 |
+
* More extension tag filtering options ([#15627](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15627))
|
30 |
+
* When saving AVIF, use JPEG's quality setting ([#15610](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15610))
|
31 |
+
* Add filename pattern: `[basename]` ([#15978](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15978))
|
32 |
+
* Add option to enable clip skip for clip L on SDXL ([#15992](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15992))
|
33 |
+
* Option to prevent screen sleep during generation ([#16001](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16001))
|
34 |
+
* ToggleLivePriview button in image viewer ([#16065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16065))
|
35 |
+
* Remove ui flashing on reloading and fast scrollong ([#16153](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16153))
|
36 |
+
* option to disable save button log.csv ([#16242](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16242))
|
37 |
+
|
38 |
+
### Extensions and API:
|
39 |
+
* Add process_before_every_sampling hook ([#15984](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15984))
|
40 |
+
* Return HTTP 400 instead of 404 on invalid sampler error ([#16140](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16140))
|
41 |
+
|
42 |
+
### Performance:
|
43 |
+
* [Performance 1/6] use_checkpoint = False ([#15803](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15803))
|
44 |
+
* [Performance 2/6] Replace einops.rearrange with torch native ops ([#15804](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15804))
|
45 |
+
* [Performance 4/6] Precompute is_sdxl_inpaint flag ([#15806](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15806))
|
46 |
+
* [Performance 5/6] Prevent unnecessary extra networks bias backup ([#15816](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15816))
|
47 |
+
* [Performance 6/6] Add --precision half option to avoid casting during inference ([#15820](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15820))
|
48 |
+
* [Performance] LDM optimization patches ([#15824](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15824))
|
49 |
+
* [Performance] Keep sigmas on CPU ([#15823](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15823))
|
50 |
+
* Check for nans in unet only once, after all steps have been completed
|
51 |
+
* Added pption to run torch profiler for image generation
|
52 |
+
|
53 |
+
### Bug Fixes:
|
54 |
+
* Fix for grids without comprehensive infotexts ([#15958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15958))
|
55 |
+
* feat: lora partial update precede full update ([#15943](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15943))
|
56 |
+
* Fix bug where file extension had an extra '.' under some circumstances ([#15893](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15893))
|
57 |
+
* Fix corrupt model initial load loop ([#15600](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15600))
|
58 |
+
* Allow old sampler names in API ([#15656](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15656))
|
59 |
+
* more old sampler scheduler compatibility ([#15681](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15681))
|
60 |
+
* Fix Hypertile xyz ([#15831](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15831))
|
61 |
+
* XYZ CSV skipinitialspace ([#15832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15832))
|
62 |
+
* fix soft inpainting on mps and xpu, torch_utils.float64 ([#15815](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15815))
|
63 |
+
* fix extention update when not on main branch ([#15797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15797))
|
64 |
+
* update pickle safe filenames
|
65 |
+
* use relative path for webui-assets css ([#15757](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15757))
|
66 |
+
* When creating a virtual environment, upgrade pip in webui.bat/webui.sh ([#15750](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15750))
|
67 |
+
* Fix AttributeError ([#15738](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15738))
|
68 |
+
* use script_path for webui root in launch_utils ([#15705](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15705))
|
69 |
+
* fix extra batch mode P Transparency ([#15664](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15664))
|
70 |
+
* use gradio theme colors in css ([#15680](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15680))
|
71 |
+
* Fix dragging text within prompt input ([#15657](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15657))
|
72 |
+
* Add correct mimetype for .mjs files ([#15654](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15654))
|
73 |
+
* QOL Items - handle metadata issues more cleanly for SD models, Loras and embeddings ([#15632](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15632))
|
74 |
+
* replace wsl-open with wslpath and explorer.exe ([#15968](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15968))
|
75 |
+
* Fix SDXL Inpaint ([#15976](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15976))
|
76 |
+
* multi size grid ([#15988](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15988))
|
77 |
+
* fix Replace preview ([#16118](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16118))
|
78 |
+
* Possible fix of wrong scale in weight decomposition ([#16151](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16151))
|
79 |
+
* Ensure use of python from venv on Mac and Linux ([#16116](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16116))
|
80 |
+
* Prioritize python3.10 over python3 if both are available on Linux and Mac (with fallback) ([#16092](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16092))
|
81 |
+
* stoping generation extras ([#16085](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16085))
|
82 |
+
* Fix SD2 loading ([#16078](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16078), [#16079](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16079))
|
83 |
+
* fix infotext Lora hashes for hires fix different lora ([#16062](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16062))
|
84 |
+
* Fix sampler scheduler autocorrection warning ([#16054](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16054))
|
85 |
+
* fix ui flashing on reloading and fast scrollong ([#16153](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16153))
|
86 |
+
* fix upscale logic ([#16239](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16239))
|
87 |
+
* [bug] do not break progressbar on non-job actions (add wrap_gradio_call_no_job) ([#16202](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16202))
|
88 |
+
* fix OSError: cannot write mode P as JPEG ([#16194](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16194))
|
89 |
+
|
90 |
+
### Other:
|
91 |
+
* fix changelog #15883 -> #15882 ([#15907](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15907))
|
92 |
+
* ReloadUI backgroundColor --background-fill-primary ([#15864](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15864))
|
93 |
+
* Use different torch versions for Intel and ARM Macs ([#15851](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15851))
|
94 |
+
* XYZ override rework ([#15836](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15836))
|
95 |
+
* scroll extensions table on overflow ([#15830](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15830))
|
96 |
+
* img2img batch upload method ([#15817](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15817))
|
97 |
+
* chore: sync v1.8.0 packages according to changelog ([#15783](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15783))
|
98 |
+
* Add AVIF MIME type support to mimetype definitions ([#15739](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15739))
|
99 |
+
* Update imageviewer.js ([#15730](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15730))
|
100 |
+
* no-referrer ([#15641](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15641))
|
101 |
+
* .gitignore trace.json ([#15980](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15980))
|
102 |
+
* Bump spandrel to 0.3.4 ([#16144](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16144))
|
103 |
+
* Defunct --max-batch-count ([#16119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16119))
|
104 |
+
* docs: update bug_report.yml ([#16102](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16102))
|
105 |
+
* Maintaining Project Compatibility for Python 3.9 Users Without Upgrade Requirements. ([#16088](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16088), [#16169](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16169), [#16192](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16192))
|
106 |
+
* Update torch for ARM Macs to 2.3.1 ([#16059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16059))
|
107 |
+
* remove deprecated setting dont_fix_second_order_samplers_schedule ([#16061](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16061))
|
108 |
+
* chore: fix typos ([#16060](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16060))
|
109 |
+
* shlex.join launch args in console log ([#16170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16170))
|
110 |
+
* activate venv .bat ([#16231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16231))
|
111 |
+
* add ids to the resize tabs in img2img ([#16218](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16218))
|
112 |
+
* update installation guide linux ([#16178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16178))
|
113 |
+
* Robust sysinfo ([#16173](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16173))
|
114 |
+
* do not send image size on paste inpaint ([#16180](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16180))
|
115 |
+
* Fix noisy DS_Store files for MacOS ([#16166](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/16166))
|
116 |
+
|
117 |
+
|
118 |
+
## 1.9.4
|
119 |
+
|
120 |
+
### Bug Fixes:
|
121 |
+
* pin setuptools version to fix the startup error ([#15882](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15882))
|
122 |
+
|
123 |
+
## 1.9.3
|
124 |
+
|
125 |
+
### Bug Fixes:
|
126 |
+
* fix get_crop_region_v2 ([#15594](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15594))
|
127 |
+
|
128 |
+
## 1.9.2
|
129 |
+
|
130 |
+
### Extensions and API:
|
131 |
+
* restore 1.8.0-style naming of scripts
|
132 |
+
|
133 |
+
## 1.9.1
|
134 |
+
|
135 |
+
### Minor:
|
136 |
+
* Add avif support ([#15582](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15582))
|
137 |
+
* Add filename patterns: `[sampler_scheduler]` and `[scheduler]` ([#15581](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15581))
|
138 |
+
|
139 |
+
### Extensions and API:
|
140 |
+
* undo adding scripts to sys.modules
|
141 |
+
* Add schedulers API endpoint ([#15577](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15577))
|
142 |
+
* Remove API upscaling factor limits ([#15560](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15560))
|
143 |
+
|
144 |
+
### Bug Fixes:
|
145 |
+
* Fix images do not match / Coordinate 'right' is less than 'left' ([#15534](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15534))
|
146 |
+
* fix: remove_callbacks_for_function should also remove from the ordered map ([#15533](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15533))
|
147 |
+
* fix x1 upscalers ([#15555](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15555))
|
148 |
+
* Fix cls.__module__ value in extension script ([#15532](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15532))
|
149 |
+
* fix typo in function call (eror -> error) ([#15531](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15531))
|
150 |
+
|
151 |
+
### Other:
|
152 |
+
* Hide 'No Image data blocks found.' message ([#15567](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15567))
|
153 |
+
* Allow webui.sh to be runnable from arbitrary directories containing a .git file ([#15561](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15561))
|
154 |
+
* Compatibility with Debian 11, Fedora 34+ and openSUSE 15.4+ ([#15544](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15544))
|
155 |
+
* numpy DeprecationWarning product -> prod ([#15547](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15547))
|
156 |
+
* get_crop_region_v2 ([#15583](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15583), [#15587](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15587))
|
157 |
+
|
158 |
+
|
159 |
+
## 1.9.0
|
160 |
+
|
161 |
+
### Features:
|
162 |
+
* Make refiner switchover based on model timesteps instead of sampling steps ([#14978](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14978))
|
163 |
+
* add an option to have old-style directory view instead of tree view; stylistic changes for extra network sorting/search controls
|
164 |
+
* add UI for reordering callbacks, support for specifying callback order in extension metadata ([#15205](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15205))
|
165 |
+
* Sgm uniform scheduler for SDXL-Lightning models ([#15325](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15325))
|
166 |
+
* Scheduler selection in main UI ([#15333](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15333), [#15361](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15361), [#15394](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15394))
|
167 |
+
|
168 |
+
### Minor:
|
169 |
+
* "open images directory" button now opens the actual dir ([#14947](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14947))
|
170 |
+
* Support inference with LyCORIS BOFT networks ([#14871](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14871), [#14973](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14973))
|
171 |
+
* make extra network card description plaintext by default, with an option to re-enable HTML as it was
|
172 |
+
* resize handle for extra networks ([#15041](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15041))
|
173 |
+
* cmd args: `--unix-filenames-sanitization` and `--filenames-max-length` ([#15031](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15031))
|
174 |
+
* show extra networks parameters in HTML table rather than raw JSON ([#15131](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15131))
|
175 |
+
* Add DoRA (weight-decompose) support for LoRA/LoHa/LoKr ([#15160](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15160), [#15283](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15283))
|
176 |
+
* Add '--no-prompt-history' cmd args for disable last generation prompt history ([#15189](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15189))
|
177 |
+
* update preview on Replace Preview ([#15201](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15201))
|
178 |
+
* only fetch updates for extensions' active git branches ([#15233](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15233))
|
179 |
+
* put upscale postprocessing UI into an accordion ([#15223](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15223))
|
180 |
+
* Support dragdrop for URLs to read infotext ([#15262](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15262))
|
181 |
+
* use diskcache library for caching ([#15287](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15287), [#15299](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15299))
|
182 |
+
* Allow PNG-RGBA for Extras Tab ([#15334](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15334))
|
183 |
+
* Support cover images embedded in safetensors metadata ([#15319](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15319))
|
184 |
+
* faster interrupt when using NN upscale ([#15380](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15380))
|
185 |
+
* Extras upscaler: an input field to limit maximul side length for the output image ([#15293](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15293), [#15415](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15415), [#15417](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15417), [#15425](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15425))
|
186 |
+
* add an option to hide postprocessing options in Extras tab
|
187 |
+
|
188 |
+
### Extensions and API:
|
189 |
+
* ResizeHandleRow - allow overriden column scale parametr ([#15004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15004))
|
190 |
+
* call script_callbacks.ui_settings_callback earlier; fix extra-options-section built-in extension killing the ui if using a setting that doesn't exist
|
191 |
+
* make it possible to use zoom.js outside webui context ([#15286](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15286), [#15288](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15288))
|
192 |
+
* allow variants for extension name in metadata.ini ([#15290](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15290))
|
193 |
+
* make reloading UI scripts optional when doing Reload UI, and off by default
|
194 |
+
* put request: gr.Request at start of img2img function similar to txt2img
|
195 |
+
* open_folder as util ([#15442](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15442))
|
196 |
+
* make it possible to import extensions' script files as `import scripts.<filename>` ([#15423](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15423))
|
197 |
+
|
198 |
+
### Performance:
|
199 |
+
* performance optimization for extra networks HTML pages
|
200 |
+
* optimization for extra networks filtering
|
201 |
+
* optimization for extra networks sorting
|
202 |
+
|
203 |
+
### Bug Fixes:
|
204 |
+
* prevent escape button causing an interrupt when no generation has been made yet
|
205 |
+
* [bug] avoid doble upscaling in inpaint ([#14966](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14966))
|
206 |
+
* possible fix for reload button not appearing in some cases for extra networks.
|
207 |
+
* fix: the `split_threshold` parameter does not work when running Split oversized images ([#15006](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15006))
|
208 |
+
* Fix resize-handle visability for vertical layout (mobile) ([#15010](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15010))
|
209 |
+
* register_tmp_file also for mtime ([#15012](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15012))
|
210 |
+
* Protect alphas_cumprod during refiner switchover ([#14979](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14979))
|
211 |
+
* Fix EXIF orientation in API image loading ([#15062](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15062))
|
212 |
+
* Only override emphasis if actually used in prompt ([#15141](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15141))
|
213 |
+
* Fix emphasis infotext missing from `params.txt` ([#15142](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15142))
|
214 |
+
* fix extract_style_text_from_prompt #15132 ([#15135](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15135))
|
215 |
+
* Fix Soft Inpaint for AnimateDiff ([#15148](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15148))
|
216 |
+
* edit-attention: deselect surrounding whitespace ([#15178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15178))
|
217 |
+
* chore: fix font not loaded ([#15183](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15183))
|
218 |
+
* use natural sort in extra networks when ordering by path
|
219 |
+
* Fix built-in lora system bugs caused by torch.nn.MultiheadAttention ([#15190](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15190))
|
220 |
+
* Avoid error from None in get_learned_conditioning ([#15191](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15191))
|
221 |
+
* Add entry to MassFileLister after writing metadata ([#15199](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15199))
|
222 |
+
* fix issue with Styles when Hires prompt is used ([#15269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15269), [#15276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15276))
|
223 |
+
* Strip comments from hires fix prompt ([#15263](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15263))
|
224 |
+
* Make imageviewer event listeners browser consistent ([#15261](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15261))
|
225 |
+
* Fix AttributeError in OFT when trying to get MultiheadAttention weight ([#15260](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15260))
|
226 |
+
* Add missing .mean() back ([#15239](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15239))
|
227 |
+
* fix "Restore progress" button ([#15221](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15221))
|
228 |
+
* fix ui-config for InputAccordion [custom_script_source] ([#15231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15231))
|
229 |
+
* handle 0 wheel deltaY ([#15268](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15268))
|
230 |
+
* prevent alt menu for firefox ([#15267](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15267))
|
231 |
+
* fix: fix syntax errors ([#15179](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15179))
|
232 |
+
* restore outputs path ([#15307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15307))
|
233 |
+
* Escape btn_copy_path filename ([#15316](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15316))
|
234 |
+
* Fix extra networks buttons when filename contains an apostrophe ([#15331](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15331))
|
235 |
+
* escape brackets in lora random prompt generator ([#15343](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15343))
|
236 |
+
* fix: Python version check for PyTorch installation compatibility ([#15390](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15390))
|
237 |
+
* fix typo in call_queue.py ([#15386](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15386))
|
238 |
+
* fix: when find already_loaded model, remove loaded by array index ([#15382](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15382))
|
239 |
+
* minor bug fix of sd model memory management ([#15350](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15350))
|
240 |
+
* Fix CodeFormer weight ([#15414](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15414))
|
241 |
+
* Fix: Remove script callbacks in ordered_callbacks_map ([#15428](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15428))
|
242 |
+
* fix limited file write (thanks, Sylwia)
|
243 |
+
* Fix extra-single-image API not doing upscale failed ([#15465](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15465))
|
244 |
+
* error handling paste_field callables ([#15470](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15470))
|
245 |
+
|
246 |
+
### Hardware:
|
247 |
+
* Add training support and change lspci for Ascend NPU ([#14981](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14981))
|
248 |
+
* Update to ROCm5.7 and PyTorch ([#14820](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14820))
|
249 |
+
* Better workaround for Navi1, removing --pre for Navi3 ([#15224](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15224))
|
250 |
+
* Ascend NPU wiki page ([#15228](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15228))
|
251 |
+
|
252 |
+
### Other:
|
253 |
+
* Update comment for Pad prompt/negative prompt v0 to add a warning about truncation, make it override the v1 implementation
|
254 |
+
* support resizable columns for touch (tablets) ([#15002](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15002))
|
255 |
+
* Fix #14591 using translated content to do categories mapping ([#14995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14995))
|
256 |
+
* Use `absolute` path for normalized filepath ([#15035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15035))
|
257 |
+
* resizeHandle handle double tap ([#15065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15065))
|
258 |
+
* --dat-models-path cmd flag ([#15039](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15039))
|
259 |
+
* Add a direct link to the binary release ([#15059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15059))
|
260 |
+
* upscaler_utils: Reduce logging ([#15084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15084))
|
261 |
+
* Fix various typos with crate-ci/typos ([#15116](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15116))
|
262 |
+
* fix_jpeg_live_preview ([#15102](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15102))
|
263 |
+
* [alternative fix] can't load webui if selected wrong extra option in ui ([#15121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15121))
|
264 |
+
* Error handling for unsupported transparency ([#14958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14958))
|
265 |
+
* Add model description to searched terms ([#15198](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15198))
|
266 |
+
* bump action version ([#15272](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15272))
|
267 |
+
* PEP 604 annotations ([#15259](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15259))
|
268 |
+
* Automatically Set the Scale by value when user selects an Upscale Model ([#15244](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15244))
|
269 |
+
* move postprocessing-for-training into builtin extensions ([#15222](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15222))
|
270 |
+
* type hinting in shared.py ([#15211](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15211))
|
271 |
+
* update ruff to 0.3.3
|
272 |
+
* Update pytorch lightning utilities ([#15310](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15310))
|
273 |
+
* Add Size as an XYZ Grid option ([#15354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15354))
|
274 |
+
* Use HF_ENDPOINT variable for HuggingFace domain with default ([#15443](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15443))
|
275 |
+
* re-add update_file_entry ([#15446](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15446))
|
276 |
+
* create_infotext allow index and callable, re-work Hires prompt infotext ([#15460](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15460))
|
277 |
+
* update restricted_opts to include more options for --hide-ui-dir-config ([#15492](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15492))
|
278 |
+
|
279 |
+
|
280 |
+
## 1.8.0
|
281 |
+
|
282 |
+
### Features:
|
283 |
+
* Update torch to version 2.1.2
|
284 |
+
* Soft Inpainting ([#14208](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14208))
|
285 |
+
* FP8 support ([#14031](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14031), [#14327](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14327))
|
286 |
+
* Support for SDXL-Inpaint Model ([#14390](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14390))
|
287 |
+
* Use Spandrel for upscaling and face restoration architectures ([#14425](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14425), [#14467](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14467), [#14473](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14473), [#14474](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14474), [#14477](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14477), [#14476](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14476), [#14484](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14484), [#14500](https://github.com/AUTOMATIC1111/stable-difusion-webui/pull/14500), [#14501](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14501), [#14504](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14504), [#14524](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14524), [#14809](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14809))
|
288 |
+
* Automatic backwards version compatibility (when loading infotexts from old images with program version specified, will add compatibility settings)
|
289 |
+
* Implement zero terminal SNR noise schedule option (**[SEED BREAKING CHANGE](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Seed-breaking-changes#180-dev-170-225-2024-01-01---zero-terminal-snr-noise-schedule-option)**, [#14145](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14145), [#14979](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14979))
|
290 |
+
* Add a [✨] button to run hires fix on selected image in the gallery (with help from [#14598](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14598), [#14626](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14626), [#14728](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14728))
|
291 |
+
* [Separate assets repository](https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets); serve fonts locally rather than from google's servers
|
292 |
+
* Official LCM Sampler Support ([#14583](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14583))
|
293 |
+
* Add support for DAT upscaler models ([#14690](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14690), [#15039](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15039))
|
294 |
+
* Extra Networks Tree View ([#14588](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14588), [#14900](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14900))
|
295 |
+
* NPU Support ([#14801](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14801))
|
296 |
+
* Prompt comments support
|
297 |
+
|
298 |
+
### Minor:
|
299 |
+
* Allow pasting in WIDTHxHEIGHT strings into the width/height fields ([#14296](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14296))
|
300 |
+
* add option: Live preview in full page image viewer ([#14230](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14230), [#14307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14307))
|
301 |
+
* Add keyboard shortcuts for generate/skip/interrupt ([#14269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14269))
|
302 |
+
* Better TCMALLOC support on different platforms ([#14227](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14227), [#14883](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14883), [#14910](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14910))
|
303 |
+
* Lora not found warning ([#14464](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14464))
|
304 |
+
* Adding negative prompts to Loras in extra networks ([#14475](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14475))
|
305 |
+
* xyz_grid: allow varying the seed along an axis separate from axis options ([#12180](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12180))
|
306 |
+
* option to convert VAE to bfloat16 (implementation of [#9295](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/9295))
|
307 |
+
* Better IPEX support ([#14229](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14229), [#14353](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14353), [#14559](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14559), [#14562](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14562), [#14597](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14597))
|
308 |
+
* Option to interrupt after current generation rather than immediately ([#13653](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13653), [#14659](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14659))
|
309 |
+
* Fullscreen Preview control fading/disable ([#14291](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14291))
|
310 |
+
* Finer settings freezing control ([#13789](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13789))
|
311 |
+
* Increase Upscaler Limits ([#14589](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14589))
|
312 |
+
* Adjust brush size with hotkeys ([#14638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14638))
|
313 |
+
* Add checkpoint info to csv log file when saving images ([#14663](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14663))
|
314 |
+
* Make more columns resizable ([#14740](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14740), [#14884](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14884))
|
315 |
+
* Add an option to not overlay original image for inpainting for #14727
|
316 |
+
* Add Pad conds v0 option to support same generation with DDIM as before 1.6.0
|
317 |
+
* Add "Interrupting..." placeholder.
|
318 |
+
* Button for refresh extensions list ([#14857](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14857))
|
319 |
+
* Add an option to disable normalization after calculating emphasis. ([#14874](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14874))
|
320 |
+
* When counting tokens, also include enabled styles (can be disabled in settings to revert to previous behavior)
|
321 |
+
* Configuration for the [📂] button for image gallery ([#14947](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14947))
|
322 |
+
* Support inference with LyCORIS BOFT networks ([#14871](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14871), [#14973](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14973))
|
323 |
+
* support resizable columns for touch (tablets) ([#15002](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15002))
|
324 |
+
|
325 |
+
### Extensions and API:
|
326 |
+
* Removed packages from requirements: basicsr, gfpgan, realesrgan; as well as their dependencies: absl-py, addict, beautifulsoup4, future, gdown, grpcio, importlib-metadata, lmdb, lpips, Markdown, platformdirs, PySocks, soupsieve, tb-nightly, tensorboard-data-server, tomli, Werkzeug, yapf, zipp, soupsieve
|
327 |
+
* Enable task ids for API ([#14314](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14314))
|
328 |
+
* add override_settings support for infotext API
|
329 |
+
* rename generation_parameters_copypaste module to infotext_utils
|
330 |
+
* prevent crash due to Script __init__ exception ([#14407](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14407))
|
331 |
+
* Bump numpy to 1.26.2 ([#14471](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14471))
|
332 |
+
* Add utility to inspect a model's dtype/device ([#14478](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14478))
|
333 |
+
* Implement general forward method for all method in built-in lora ext ([#14547](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14547))
|
334 |
+
* Execute model_loaded_callback after moving to target device ([#14563](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14563))
|
335 |
+
* Add self to CFGDenoiserParams ([#14573](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14573))
|
336 |
+
* Allow TLS with API only mode (--nowebui) ([#14593](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14593))
|
337 |
+
* New callback: postprocess_image_after_composite ([#14657](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14657))
|
338 |
+
* modules/api/api.py: add api endpoint to refresh embeddings list ([#14715](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14715))
|
339 |
+
* set_named_arg ([#14773](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14773))
|
340 |
+
* add before_token_counter callback and use it for prompt comments
|
341 |
+
* ResizeHandleRow - allow overridden column scale parameter ([#15004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15004))
|
342 |
+
|
343 |
+
### Performance:
|
344 |
+
* Massive performance improvement for extra networks directories with a huge number of files in them in an attempt to tackle #14507 ([#14528](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14528))
|
345 |
+
* Reduce unnecessary re-indexing extra networks directory ([#14512](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14512))
|
346 |
+
* Avoid unnecessary `isfile`/`exists` calls ([#14527](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14527))
|
347 |
+
|
348 |
+
### Bug Fixes:
|
349 |
+
* fix multiple bugs related to styles multi-file support ([#14203](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14203), [#14276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14276), [#14707](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14707))
|
350 |
+
* Lora fixes ([#14300](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14300), [#14237](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14237), [#14546](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14546), [#14726](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14726))
|
351 |
+
* Re-add setting lost as part of e294e46 ([#14266](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14266))
|
352 |
+
* fix extras caption BLIP ([#14330](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14330))
|
353 |
+
* include infotext into saved init image for img2img ([#14452](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14452))
|
354 |
+
* xyz grid handle axis_type is None ([#14394](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14394))
|
355 |
+
* Update Added (Fixed) IPV6 Functionality When there is No Webui Argument Passed webui.py ([#14354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14354))
|
356 |
+
* fix API thread safe issues of txt2img and img2img ([#14421](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14421))
|
357 |
+
* handle selectable script_index is None ([#14487](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14487))
|
358 |
+
* handle config.json failed to load ([#14525](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14525), [#14767](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14767))
|
359 |
+
* paste infotext cast int as float ([#14523](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14523))
|
360 |
+
* Ensure GRADIO_ANALYTICS_ENABLED is set early enough ([#14537](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14537))
|
361 |
+
* Fix logging configuration again ([#14538](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14538))
|
362 |
+
* Handle CondFunc exception when resolving attributes ([#14560](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14560))
|
363 |
+
* Fix extras big batch crashes ([#14699](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14699))
|
364 |
+
* Fix using wrong model caused by alias ([#14655](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14655))
|
365 |
+
* Add # to the invalid_filename_chars list ([#14640](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14640))
|
366 |
+
* Fix extension check for requirements ([#14639](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14639))
|
367 |
+
* Fix tab indexes are reset after restart UI ([#14637](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14637))
|
368 |
+
* Fix nested manual cast ([#14689](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14689))
|
369 |
+
* Keep postprocessing upscale selected tab after restart ([#14702](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14702))
|
370 |
+
* XYZ grid: filter out blank vals when axis is int or float type (like int axis seed) ([#14754](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14754))
|
371 |
+
* fix CLIP Interrogator topN regex ([#14775](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14775))
|
372 |
+
* Fix dtype error in MHA layer/change dtype checking mechanism for manual cast ([#14791](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14791))
|
373 |
+
* catch load style.csv error ([#14814](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14814))
|
374 |
+
* fix error when editing extra networks card
|
375 |
+
* fix extra networks metadata failing to work properly when you create the .json file with metadata for the first time.
|
376 |
+
* util.walk_files extensions case insensitive ([#14879](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14879))
|
377 |
+
* if extensions page not loaded, prevent apply ([#14873](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14873))
|
378 |
+
* call the right function for token counter in img2img
|
379 |
+
* Fix the bugs that search/reload will disappear when using other ExtraNetworks extensions ([#14939](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14939))
|
380 |
+
* Gracefully handle mtime read exception from cache ([#14933](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14933))
|
381 |
+
* Only trigger interrupt on `Esc` when interrupt button visible ([#14932](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14932))
|
382 |
+
* Disable prompt token counters option actually disables token counting rather than just hiding results.
|
383 |
+
* avoid double upscaling in inpaint ([#14966](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14966))
|
384 |
+
* Fix #14591 using translated content to do categories mapping ([#14995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14995))
|
385 |
+
* fix: the `split_threshold` parameter does not work when running Split oversized images ([#15006](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15006))
|
386 |
+
* Fix resize-handle for mobile ([#15010](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15010), [#15065](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15065))
|
387 |
+
|
388 |
+
### Other:
|
389 |
+
* Assign id for "extra_options". Replace numeric field with slider. ([#14270](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14270))
|
390 |
+
* change state dict comparison to ref compare ([#14216](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14216))
|
391 |
+
* Bump torch-rocm to 5.6/5.7 ([#14293](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14293))
|
392 |
+
* Base output path off data path ([#14446](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14446))
|
393 |
+
* reorder training preprocessing modules in extras tab ([#14367](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14367))
|
394 |
+
* Remove `cleanup_models` code ([#14472](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14472))
|
395 |
+
* only rewrite ui-config when there is change ([#14352](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14352))
|
396 |
+
* Fix lint issue from 501993eb ([#14495](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14495))
|
397 |
+
* Update README.md ([#14548](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14548))
|
398 |
+
* hires button, fix seeds ()
|
399 |
+
* Logging: set formatter correctly for fallback logger too ([#14618](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14618))
|
400 |
+
* Read generation info from infotexts rather than json for internal needs (save, extract seed from generated pic) ([#14645](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14645))
|
401 |
+
* improve get_crop_region ([#14709](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14709))
|
402 |
+
* Bump safetensors' version to 0.4.2 ([#14782](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14782))
|
403 |
+
* add tooltip create_submit_box ([#14803](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14803))
|
404 |
+
* extensions tab table row hover highlight ([#14885](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14885))
|
405 |
+
* Always add timestamp to displayed image ([#14890](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14890))
|
406 |
+
* Added core.filemode=false so doesn't track changes in file permission… ([#14930](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14930))
|
407 |
+
* Normalize command-line argument paths ([#14934](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14934), [#15035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15035))
|
408 |
+
* Use original App Title in progress bar ([#14916](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14916))
|
409 |
+
* register_tmp_file also for mtime ([#15012](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15012))
|
410 |
+
|
411 |
+
## 1.7.0
|
412 |
+
|
413 |
+
### Features:
|
414 |
+
* settings tab rework: add search field, add categories, split UI settings page into many
|
415 |
+
* add altdiffusion-m18 support ([#13364](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13364))
|
416 |
+
* support inference with LyCORIS GLora networks ([#13610](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13610))
|
417 |
+
* add lora-embedding bundle system ([#13568](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13568))
|
418 |
+
* option to move prompt from top row into generation parameters
|
419 |
+
* add support for SSD-1B ([#13865](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13865))
|
420 |
+
* support inference with OFT networks ([#13692](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13692))
|
421 |
+
* script metadata and DAG sorting mechanism ([#13944](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13944))
|
422 |
+
* support HyperTile optimization ([#13948](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13948))
|
423 |
+
* add support for SD 2.1 Turbo ([#14170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14170))
|
424 |
+
* remove Train->Preprocessing tab and put all its functionality into Extras tab
|
425 |
+
* initial IPEX support for Intel Arc GPU ([#14171](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14171))
|
426 |
+
|
427 |
+
### Minor:
|
428 |
+
* allow reading model hash from images in img2img batch mode ([#12767](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12767))
|
429 |
+
* add option to align with sgm repo's sampling implementation ([#12818](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12818))
|
430 |
+
* extra field for lora metadata viewer: `ss_output_name` ([#12838](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12838))
|
431 |
+
* add action in settings page to calculate all SD checkpoint hashes ([#12909](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12909))
|
432 |
+
* add button to copy prompt to style editor ([#12975](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12975))
|
433 |
+
* add --skip-load-model-at-start option ([#13253](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13253))
|
434 |
+
* write infotext to gif images
|
435 |
+
* read infotext from gif images ([#13068](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13068))
|
436 |
+
* allow configuring the initial state of InputAccordion in ui-config.json ([#13189](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13189))
|
437 |
+
* allow editing whitespace delimiters for ctrl+up/ctrl+down prompt editing ([#13444](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13444))
|
438 |
+
* prevent accidentally closing popup dialogs ([#13480](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13480))
|
439 |
+
* added option to play notification sound or not ([#13631](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13631))
|
440 |
+
* show the preview image in the full screen image viewer if available ([#13459](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13459))
|
441 |
+
* support for webui.settings.bat ([#13638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13638))
|
442 |
+
* add an option to not print stack traces on ctrl+c
|
443 |
+
* start/restart generation by Ctrl (Alt) + Enter ([#13644](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13644))
|
444 |
+
* update prompts_from_file script to allow concatenating entries with the general prompt ([#13733](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13733))
|
445 |
+
* added a visible checkbox to input accordion
|
446 |
+
* added an option to hide all txt2img/img2img parameters in an accordion ([#13826](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13826))
|
447 |
+
* added 'Path' sorting option for Extra network cards ([#13968](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13968))
|
448 |
+
* enable prompt hotkeys in style editor ([#13931](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13931))
|
449 |
+
* option to show batch img2img results in UI ([#14009](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14009))
|
450 |
+
* infotext updates: add option to disregard certain infotext fields, add option to not include VAE in infotext, add explanation to infotext settings page, move some options to infotext settings page
|
451 |
+
* add FP32 fallback support on sd_vae_approx ([#14046](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14046))
|
452 |
+
* support XYZ scripts / split hires path from unet ([#14126](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14126))
|
453 |
+
* allow use of multiple styles csv files ([#14125](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14125))
|
454 |
+
* make extra network card description plaintext by default, with an option (Treat card description as HTML) to re-enable HTML as it was (originally by [#13241](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13241))
|
455 |
+
|
456 |
+
### Extensions and API:
|
457 |
+
* update gradio to 3.41.2
|
458 |
+
* support installed extensions list api ([#12774](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12774))
|
459 |
+
* update pnginfo API to return dict with parsed values
|
460 |
+
* add noisy latent to `ExtraNoiseParams` for callback ([#12856](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12856))
|
461 |
+
* show extension datetime in UTC ([#12864](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12864), [#12865](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12865), [#13281](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13281))
|
462 |
+
* add an option to choose how to combine hires fix and refiner
|
463 |
+
* include program version in info response. ([#13135](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13135))
|
464 |
+
* sd_unet support for SDXL
|
465 |
+
* patch DDPM.register_betas so that users can put given_betas in model yaml ([#13276](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13276))
|
466 |
+
* xyz_grid: add prepare ([#13266](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13266))
|
467 |
+
* allow multiple localization files with same language in extensions ([#13077](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13077))
|
468 |
+
* add onEdit function for js and rework token-counter.js to use it
|
469 |
+
* fix the key error exception when processing override_settings keys ([#13567](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13567))
|
470 |
+
* ability for extensions to return custom data via api in response.images ([#13463](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13463))
|
471 |
+
* call state.jobnext() before postproces*() ([#13762](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13762))
|
472 |
+
* add option to set notification sound volume ([#13884](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13884))
|
473 |
+
* update Ruff to 0.1.6 ([#14059](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14059))
|
474 |
+
* add Block component creation callback ([#14119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14119))
|
475 |
+
* catch uncaught exception with ui creation scripts ([#14120](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14120))
|
476 |
+
* use extension name for determining an extension is installed in the index ([#14063](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14063))
|
477 |
+
* update is_installed() from launch_utils.py to fix reinstalling already installed packages ([#14192](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14192))
|
478 |
+
|
479 |
+
### Bug Fixes:
|
480 |
+
* fix pix2pix producing bad results
|
481 |
+
* fix defaults settings page breaking when any of main UI tabs are hidden
|
482 |
+
* fix error that causes some extra networks to be disabled if both <lora:> and <lyco:> are present in the prompt
|
483 |
+
* fix for Reload UI function: if you reload UI on one tab, other opened tabs will no longer stop working
|
484 |
+
* prevent duplicate resize handler ([#12795](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12795))
|
485 |
+
* small typo: vae resolve bug ([#12797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12797))
|
486 |
+
* hide broken image crop tool ([#12792](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12792))
|
487 |
+
* don't show hidden samplers in dropdown for XYZ script ([#12780](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12780))
|
488 |
+
* fix style editing dialog breaking if it's opened in both img2img and txt2img tabs
|
489 |
+
* hide --gradio-auth and --api-auth values from /internal/sysinfo report
|
490 |
+
* add missing infotext for RNG in options ([#12819](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12819))
|
491 |
+
* fix notification not playing when built-in webui tab is inactive ([#12834](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12834))
|
492 |
+
* honor `--skip-install` for extension installers ([#12832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832))
|
493 |
+
* don't print blank stdout in extension installers ([#12833](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12833), [#12855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12855))
|
494 |
+
* get progressbar to display correctly in extensions tab
|
495 |
+
* keep order in list of checkpoints when loading model that doesn't have a checksum
|
496 |
+
* fix inpainting models in txt2img creating black pictures
|
497 |
+
* fix generation params regex ([#12876](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12876))
|
498 |
+
* fix batch img2img output dir with script ([#12926](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12926))
|
499 |
+
* fix #13080 - Hypernetwork/TI preview generation ([#13084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13084))
|
500 |
+
* fix bug with sigma min/max overrides. ([#12995](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12995))
|
501 |
+
* more accurate check for enabling cuDNN benchmark on 16XX cards ([#12924](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12924))
|
502 |
+
* don't use multicond parser for negative prompt counter ([#13118](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13118))
|
503 |
+
* fix data-sort-name containing spaces ([#13412](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13412))
|
504 |
+
* update card on correct tab when editing metadata ([#13411](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13411))
|
505 |
+
* fix viewing/editing metadata when filename contains an apostrophe ([#13395](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13395))
|
506 |
+
* fix: --sd_model in "Prompts from file or textbox" script is not working ([#13302](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13302))
|
507 |
+
* better Support for Portable Git ([#13231](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13231))
|
508 |
+
* fix issues when webui_dir is not work_dir ([#13210](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13210))
|
509 |
+
* fix: lora-bias-backup don't reset cache ([#13178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13178))
|
510 |
+
* account for customizable extra network separators whyen removing extra network text from the prompt ([#12877](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12877))
|
511 |
+
* re fix batch img2img output dir with script ([#13170](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13170))
|
512 |
+
* fix `--ckpt-dir` path separator and option use `short name` for checkpoint dropdown ([#13139](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13139))
|
513 |
+
* consolidated allowed preview formats, Fix extra network `.gif` not woking as preview ([#13121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13121))
|
514 |
+
* fix venv_dir=- environment variable not working as expected on linux ([#13469](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13469))
|
515 |
+
* repair unload sd checkpoint button
|
516 |
+
* edit-attention fixes ([#13533](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13533))
|
517 |
+
* fix bug when using --gfpgan-models-path ([#13718](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13718))
|
518 |
+
* properly apply sort order for extra network cards when selected from dropdown
|
519 |
+
* fixes generation restart not working for some users when 'Ctrl+Enter' is pressed ([#13962](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13962))
|
520 |
+
* thread safe extra network list_items ([#13014](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13014))
|
521 |
+
* fix not able to exit metadata popup when pop up is too big ([#14156](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14156))
|
522 |
+
* fix auto focal point crop for opencv >= 4.8 ([#14121](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14121))
|
523 |
+
* make 'use-cpu all' actually apply to 'all' ([#14131](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14131))
|
524 |
+
* extras tab batch: actually use original filename
|
525 |
+
* make webui not crash when running with --disable-all-extensions option
|
526 |
+
|
527 |
+
### Other:
|
528 |
+
* non-local condition ([#12814](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12814))
|
529 |
+
* fix minor typos ([#12827](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12827))
|
530 |
+
* remove xformers Python version check ([#12842](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12842))
|
531 |
+
* style: file-metadata word-break ([#12837](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12837))
|
532 |
+
* revert SGM noise multiplier change for img2img because it breaks hires fix
|
533 |
+
* do not change quicksettings dropdown option when value returned is `None` ([#12854](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12854))
|
534 |
+
* [RC 1.6.0 - zoom is partly hidden] Update style.css ([#12839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12839))
|
535 |
+
* chore: change extension time format ([#12851](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12851))
|
536 |
+
* WEBUI.SH - Use torch 2.1.0 release candidate for Navi 3 ([#12929](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12929))
|
537 |
+
* add Fallback at images.read_info_from_image if exif data was invalid ([#13028](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13028))
|
538 |
+
* update cmd arg description ([#12986](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12986))
|
539 |
+
* fix: update shared.opts.data when add_option ([#12957](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12957), [#13213](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13213))
|
540 |
+
* restore missing tooltips ([#12976](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12976))
|
541 |
+
* use default dropdown padding on mobile ([#12880](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12880))
|
542 |
+
* put enable console prompts option into settings from commandline args ([#13119](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13119))
|
543 |
+
* fix some deprecated types ([#12846](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12846))
|
544 |
+
* bump to torchsde==0.2.6 ([#13418](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13418))
|
545 |
+
* update dragdrop.js ([#13372](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13372))
|
546 |
+
* use orderdict as lru cache:opt/bug ([#13313](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13313))
|
547 |
+
* XYZ if not include sub grids do not save sub grid ([#13282](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13282))
|
548 |
+
* initialize state.time_start befroe state.job_count ([#13229](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13229))
|
549 |
+
* fix fieldname regex ([#13458](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13458))
|
550 |
+
* change denoising_strength default to None. ([#13466](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13466))
|
551 |
+
* fix regression ([#13475](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13475))
|
552 |
+
* fix IndexError ([#13630](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13630))
|
553 |
+
* fix: checkpoints_loaded:{checkpoint:state_dict}, model.load_state_dict issue in dict value empty ([#13535](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13535))
|
554 |
+
* update bug_report.yml ([#12991](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12991))
|
555 |
+
* requirements_versions httpx==0.24.1 ([#13839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13839))
|
556 |
+
* fix parenthesis auto selection ([#13829](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13829))
|
557 |
+
* fix #13796 ([#13797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13797))
|
558 |
+
* corrected a typo in `modules/cmd_args.py` ([#13855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13855))
|
559 |
+
* feat: fix randn found element of type float at pos 2 ([#14004](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14004))
|
560 |
+
* adds tqdm handler to logging_config.py for progress bar integration ([#13996](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13996))
|
561 |
+
* hotfix: call shared.state.end() after postprocessing done ([#13977](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13977))
|
562 |
+
* fix dependency address patch 1 ([#13929](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13929))
|
563 |
+
* save sysinfo as .json ([#14035](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14035))
|
564 |
+
* move exception_records related methods to errors.py ([#14084](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14084))
|
565 |
+
* compatibility ([#13936](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13936))
|
566 |
+
* json.dump(ensure_ascii=False) ([#14108](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14108))
|
567 |
+
* dir buttons start with / so only the correct dir will be shown and no… ([#13957](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13957))
|
568 |
+
* alternate implementation for unet forward replacement that does not depend on hijack being applied
|
569 |
+
* re-add `keyedit_delimiters_whitespace` setting lost as part of commit e294e46 ([#14178](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14178))
|
570 |
+
* fix `save_samples` being checked early when saving masked composite ([#14177](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14177))
|
571 |
+
* slight optimization for mask and mask_composite ([#14181](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14181))
|
572 |
+
* add import_hook hack to work around basicsr/torchvision incompatibility ([#14186](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/14186))
|
573 |
+
|
574 |
+
## 1.6.1
|
575 |
+
|
576 |
+
### Bug Fixes:
|
577 |
+
* fix an error causing the webui to fail to start ([#13839](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/13839))
|
578 |
+
|
579 |
+
## 1.6.0
|
580 |
+
|
581 |
+
### Features:
|
582 |
+
* refiner support [#12371](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12371)
|
583 |
+
* add NV option for Random number generator source setting, which allows to generate same pictures on CPU/AMD/Mac as on NVidia videocards
|
584 |
+
* add style editor dialog
|
585 |
+
* hires fix: add an option to use a different checkpoint for second pass ([#12181](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12181))
|
586 |
+
* option to keep multiple loaded models in memory ([#12227](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12227))
|
587 |
+
* new samplers: Restart, DPM++ 2M SDE Exponential, DPM++ 2M SDE Heun, DPM++ 2M SDE Heun Karras, DPM++ 2M SDE Heun Exponential, DPM++ 3M SDE, DPM++ 3M SDE Karras, DPM++ 3M SDE Exponential ([#12300](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12300), [#12519](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12519), [#12542](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12542))
|
588 |
+
* rework DDIM, PLMS, UniPC to use CFG denoiser same as in k-diffusion samplers:
|
589 |
+
* makes all of them work with img2img
|
590 |
+
* makes prompt composition possible (AND)
|
591 |
+
* makes them available for SDXL
|
592 |
+
* always show extra networks tabs in the UI ([#11808](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/11808))
|
593 |
+
* use less RAM when creating models ([#11958](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/11958), [#12599](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12599))
|
594 |
+
* textual inversion inference support for SDXL
|
595 |
+
* extra networks UI: show metadata for SD checkpoints
|
596 |
+
* checkpoint merger: add metadata support
|
597 |
+
* prompt editing and attention: add support for whitespace after the number ([ red : green : 0.5 ]) (seed breaking change) ([#12177](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12177))
|
598 |
+
* VAE: allow selecting own VAE for each checkpoint (in user metadata editor)
|
599 |
+
* VAE: add selected VAE to infotext
|
600 |
+
* options in main UI: add own separate setting for txt2img and img2img, correctly read values from pasted infotext, add setting for column count ([#12551](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12551))
|
601 |
+
* add resize handle to txt2img and img2img tabs, allowing to change the amount of horizontable space given to generation parameters and resulting image gallery ([#12687](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12687), [#12723](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12723))
|
602 |
+
* change default behavior for batching cond/uncond -- now it's on by default, and is disabled by an UI setting (Optimizatios -> Batch cond/uncond) - if you are on lowvram/medvram and are getting OOM exceptions, you will need to enable it
|
603 |
+
* show current position in queue and make it so that requests are processed in the order of arrival ([#12707](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12707))
|
604 |
+
* add `--medvram-sdxl` flag that only enables `--medvram` for SDXL models
|
605 |
+
* prompt editing timeline has separate range for first pass and hires-fix pass (seed breaking change) ([#12457](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12457))
|
606 |
+
|
607 |
+
### Minor:
|
608 |
+
* img2img batch: RAM savings, VRAM savings, .tif, .tiff in img2img batch ([#12120](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12120), [#12514](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12514), [#12515](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12515))
|
609 |
+
* postprocessing/extras: RAM savings ([#12479](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12479))
|
610 |
+
* XYZ: in the axis labels, remove pathnames from model filenames
|
611 |
+
* XYZ: support hires sampler ([#12298](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12298))
|
612 |
+
* XYZ: new option: use text inputs instead of dropdowns ([#12491](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12491))
|
613 |
+
* add gradio version warning
|
614 |
+
* sort list of VAE checkpoints ([#12297](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12297))
|
615 |
+
* use transparent white for mask in inpainting, along with an option to select the color ([#12326](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12326))
|
616 |
+
* move some settings to their own section: img2img, VAE
|
617 |
+
* add checkbox to show/hide dirs for extra networks
|
618 |
+
* Add TAESD(or more) options for all the VAE encode/decode operation ([#12311](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12311))
|
619 |
+
* gradio theme cache, new gradio themes, along with explanation that the user can input his own values ([#12346](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12346), [#12355](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12355))
|
620 |
+
* sampler fixes/tweaks: s_tmax, s_churn, s_noise, s_tmax ([#12354](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12354), [#12356](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12356), [#12357](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12357), [#12358](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12358), [#12375](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12375), [#12521](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12521))
|
621 |
+
* update README.md with correct instructions for Linux installation ([#12352](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12352))
|
622 |
+
* option to not save incomplete images, on by default ([#12338](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12338))
|
623 |
+
* enable cond cache by default
|
624 |
+
* git autofix for repos that are corrupted ([#12230](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12230))
|
625 |
+
* allow to open images in new browser tab by middle mouse button ([#12379](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12379))
|
626 |
+
* automatically open webui in browser when running "locally" ([#12254](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12254))
|
627 |
+
* put commonly used samplers on top, make DPM++ 2M Karras the default choice
|
628 |
+
* zoom and pan: option to auto-expand a wide image, improved integration ([#12413](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12413), [#12727](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12727))
|
629 |
+
* option to cache Lora networks in memory
|
630 |
+
* rework hires fix UI to use accordion
|
631 |
+
* face restoration and tiling moved to settings - use "Options in main UI" setting if you want them back
|
632 |
+
* change quicksettings items to have variable width
|
633 |
+
* Lora: add Norm module, add support for bias ([#12503](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12503))
|
634 |
+
* Lora: output warnings in UI rather than fail for unfitting loras; switch to logging for error output in console
|
635 |
+
* support search and display of hashes for all extra network items ([#12510](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12510))
|
636 |
+
* add extra noise param for img2img operations ([#12564](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12564))
|
637 |
+
* support for Lora with bias ([#12584](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12584))
|
638 |
+
* make interrupt quicker ([#12634](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12634))
|
639 |
+
* configurable gallery height ([#12648](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12648))
|
640 |
+
* make results column sticky ([#12645](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12645))
|
641 |
+
* more hash filename patterns ([#12639](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12639))
|
642 |
+
* make image viewer actually fit the whole page ([#12635](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12635))
|
643 |
+
* make progress bar work independently from live preview display which results in it being updated a lot more often
|
644 |
+
* forbid Full live preview method for medvram and add a setting to undo the forbidding
|
645 |
+
* make it possible to localize tooltips and placeholders
|
646 |
+
* add option to align with sgm repo's sampling implementation ([#12818](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12818))
|
647 |
+
* Restore faces and Tiling generation parameters have been moved to settings out of main UI
|
648 |
+
* if you want to put them back into main UI, use `Options in main UI` setting on the UI page.
|
649 |
+
|
650 |
+
### Extensions and API:
|
651 |
+
* gradio 3.41.2
|
652 |
+
* also bump versions for packages: transformers, GitPython, accelerate, scikit-image, timm, tomesd
|
653 |
+
* support tooltip kwarg for gradio elements: gr.Textbox(label='hello', tooltip='world')
|
654 |
+
* properly clear the total console progressbar when using txt2img and img2img from API
|
655 |
+
* add cmd_arg --disable-extra-extensions and --disable-all-extensions ([#12294](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12294))
|
656 |
+
* shared.py and webui.py split into many files
|
657 |
+
* add --loglevel commandline argument for logging
|
658 |
+
* add a custom UI element that combines accordion and checkbox
|
659 |
+
* avoid importing gradio in tests because it spams warnings
|
660 |
+
* put infotext label for setting into OptionInfo definition rather than in a separate list
|
661 |
+
* make `StableDiffusionProcessingImg2Img.mask_blur` a property, make more inline with PIL `GaussianBlur` ([#12470](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12470))
|
662 |
+
* option to make scripts UI without gr.Group
|
663 |
+
* add a way for scripts to register a callback for before/after just a single component's creation
|
664 |
+
* use dataclass for StableDiffusionProcessing
|
665 |
+
* store patches for Lora in a specialized module instead of inside torch
|
666 |
+
* support http/https URLs in API ([#12663](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12663), [#12698](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12698))
|
667 |
+
* add extra noise callback ([#12616](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12616))
|
668 |
+
* dump current stack traces when exiting with SIGINT
|
669 |
+
* add type annotations for extra fields of shared.sd_model
|
670 |
+
|
671 |
+
### Bug Fixes:
|
672 |
+
* Don't crash if out of local storage quota for javascriot localStorage
|
673 |
+
* XYZ plot do not fail if an exception occurs
|
674 |
+
* fix missing TI hash in infotext if generation uses both negative and positive TI ([#12269](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12269))
|
675 |
+
* localization fixes ([#12307](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12307))
|
676 |
+
* fix sdxl model invalid configuration after the hijack
|
677 |
+
* correctly toggle extras checkbox for infotext paste ([#12304](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12304))
|
678 |
+
* open raw sysinfo link in new page ([#12318](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12318))
|
679 |
+
* prompt parser: Account for empty field in alternating words syntax ([#12319](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12319))
|
680 |
+
* add tab and carriage return to invalid filename chars ([#12327](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12327))
|
681 |
+
* fix api only Lora not working ([#12387](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12387))
|
682 |
+
* fix options in main UI misbehaving when there's just one element
|
683 |
+
* make it possible to use a sampler from infotext even if it's hidden in the dropdown
|
684 |
+
* fix styles missing from the prompt in infotext when making a grid of batch of multiplie images
|
685 |
+
* prevent bogus progress output in console when calculating hires fix dimensions
|
686 |
+
* fix --use-textbox-seed
|
687 |
+
* fix broken `Lora/Networks: use old method` option ([#12466](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12466))
|
688 |
+
* properly return `None` for VAE hash when using `--no-hashing` ([#12463](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12463))
|
689 |
+
* MPS/macOS fixes and optimizations ([#12526](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12526))
|
690 |
+
* add second_order to samplers that mistakenly didn't have it
|
691 |
+
* when refreshing cards in extra networks UI, do not discard user's custom resolution
|
692 |
+
* fix processing error that happens if batch_size is not a multiple of how many prompts/negative prompts there are ([#12509](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12509))
|
693 |
+
* fix inpaint upload for alpha masks ([#12588](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12588))
|
694 |
+
* fix exception when image sizes are not integers ([#12586](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12586))
|
695 |
+
* fix incorrect TAESD Latent scale ([#12596](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12596))
|
696 |
+
* auto add data-dir to gradio-allowed-path ([#12603](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12603))
|
697 |
+
* fix exception if extensuions dir is missing ([#12607](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12607))
|
698 |
+
* fix issues with api model-refresh and vae-refresh ([#12638](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12638))
|
699 |
+
* fix img2img background color for transparent images option not being used ([#12633](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12633))
|
700 |
+
* attempt to resolve NaN issue with unstable VAEs in fp32 mk2 ([#12630](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12630))
|
701 |
+
* implement missing undo hijack for SDXL
|
702 |
+
* fix xyz swap axes ([#12684](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12684))
|
703 |
+
* fix errors in backup/restore tab if any of config files are broken ([#12689](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12689))
|
704 |
+
* fix SD VAE switch error after model reuse ([#12685](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12685))
|
705 |
+
* fix trying to create images too large for the chosen format ([#12667](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12667))
|
706 |
+
* create Gradio temp directory if necessary ([#12717](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12717))
|
707 |
+
* prevent possible cache loss if exiting as it's being written by using an atomic operation to replace the cache with the new version
|
708 |
+
* set devices.dtype_unet correctly
|
709 |
+
* run RealESRGAN on GPU for non-CUDA devices ([#12737](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737))
|
710 |
+
* prevent extra network buttons being obscured by description for very small card sizes ([#12745](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12745))
|
711 |
+
* fix error that causes some extra networks to be disabled if both <lora:> and <lyco:> are present in the prompt
|
712 |
+
* fix defaults settings page breaking when any of main UI tabs are hidden
|
713 |
+
* fix incorrect save/display of new values in Defaults page in settings
|
714 |
+
* fix for Reload UI function: if you reload UI on one tab, other opened tabs will no longer stop working
|
715 |
+
* fix an error that prevents VAE being reloaded after an option change if a VAE near the checkpoint exists ([#12797](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737))
|
716 |
+
* hide broken image crop tool ([#12792](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737))
|
717 |
+
* don't show hidden samplers in dropdown for XYZ script ([#12780](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12737))
|
718 |
+
* fix style editing dialog breaking if it's opened in both img2img and txt2img tabs
|
719 |
+
* fix a bug allowing users to bypass gradio and API authentication (reported by vysecurity)
|
720 |
+
* fix notification not playing when built-in webui tab is inactive ([#12834](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12834))
|
721 |
+
* honor `--skip-install` for extension installers ([#12832](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832))
|
722 |
+
* don't print blank stdout in extension installers ([#12833](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12832), [#12855](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12855))
|
723 |
+
* do not change quicksettings dropdown option when value returned is `None` ([#12854](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/12854))
|
724 |
+
* get progressbar to display correctly in extensions tab
|
725 |
+
|
726 |
+
|
727 |
+
## 1.5.2
|
728 |
+
|
729 |
+
### Bug Fixes:
|
730 |
+
* fix memory leak when generation fails
|
731 |
+
* update doggettx cross attention optimization to not use an unreasonable amount of memory in some edge cases -- suggestion by MorkTheOrk
|
732 |
+
|
733 |
+
|
734 |
+
## 1.5.1
|
735 |
+
|
736 |
+
### Minor:
|
737 |
+
* support parsing text encoder blocks in some new LoRAs
|
738 |
+
* delete scale checker script due to user demand
|
739 |
+
|
740 |
+
### Extensions and API:
|
741 |
+
* add postprocess_batch_list script callback
|
742 |
+
|
743 |
+
### Bug Fixes:
|
744 |
+
* fix TI training for SD1
|
745 |
+
* fix reload altclip model error
|
746 |
+
* prepend the pythonpath instead of overriding it
|
747 |
+
* fix typo in SD_WEBUI_RESTARTING
|
748 |
+
* if txt2img/img2img raises an exception, finally call state.end()
|
749 |
+
* fix composable diffusion weight parsing
|
750 |
+
* restyle Startup profile for black users
|
751 |
+
* fix webui not launching with --nowebui
|
752 |
+
* catch exception for non git extensions
|
753 |
+
* fix some options missing from /sdapi/v1/options
|
754 |
+
* fix for extension update status always saying "unknown"
|
755 |
+
* fix display of extra network cards that have `<>` in the name
|
756 |
+
* update lora extension to work with python 3.8
|
757 |
+
|
758 |
+
|
759 |
+
## 1.5.0
|
760 |
+
|
761 |
+
### Features:
|
762 |
+
* SD XL support
|
763 |
+
* user metadata system for custom networks
|
764 |
+
* extended Lora metadata editor: set activation text, default weight, view tags, training info
|
765 |
+
* Lora extension rework to include other types of networks (all that were previously handled by LyCORIS extension)
|
766 |
+
* show github stars for extensions
|
767 |
+
* img2img batch mode can read extra stuff from png info
|
768 |
+
* img2img batch works with subdirectories
|
769 |
+
* hotkeys to move prompt elements: alt+left/right
|
770 |
+
* restyle time taken/VRAM display
|
771 |
+
* add textual inversion hashes to infotext
|
772 |
+
* optimization: cache git extension repo information
|
773 |
+
* move generate button next to the generated picture for mobile clients
|
774 |
+
* hide cards for networks of incompatible Stable Diffusion version in Lora extra networks interface
|
775 |
+
* skip installing packages with pip if they all are already installed - startup speedup of about 2 seconds
|
776 |
+
|
777 |
+
### Minor:
|
778 |
+
* checkbox to check/uncheck all extensions in the Installed tab
|
779 |
+
* add gradio user to infotext and to filename patterns
|
780 |
+
* allow gif for extra network previews
|
781 |
+
* add options to change colors in grid
|
782 |
+
* use natural sort for items in extra networks
|
783 |
+
* Mac: use empty_cache() from torch 2 to clear VRAM
|
784 |
+
* added automatic support for installing the right libraries for Navi3 (AMD)
|
785 |
+
* add option SWIN_torch_compile to accelerate SwinIR upscale
|
786 |
+
* suppress printing TI embedding info at start to console by default
|
787 |
+
* speedup extra networks listing
|
788 |
+
* added `[none]` filename token.
|
789 |
+
* removed thumbs extra networks view mode (use settings tab to change width/height/scale to get thumbs)
|
790 |
+
* add always_discard_next_to_last_sigma option to XYZ plot
|
791 |
+
* automatically switch to 32-bit float VAE if the generated picture has NaNs without the need for `--no-half-vae` commandline flag.
|
792 |
+
|
793 |
+
### Extensions and API:
|
794 |
+
* api endpoints: /sdapi/v1/server-kill, /sdapi/v1/server-restart, /sdapi/v1/server-stop
|
795 |
+
* allow Script to have custom metaclass
|
796 |
+
* add model exists status check /sdapi/v1/options
|
797 |
+
* rename --add-stop-route to --api-server-stop
|
798 |
+
* add `before_hr` script callback
|
799 |
+
* add callback `after_extra_networks_activate`
|
800 |
+
* disable rich exception output in console for API by default, use WEBUI_RICH_EXCEPTIONS env var to enable
|
801 |
+
* return http 404 when thumb file not found
|
802 |
+
* allow replacing extensions index with environment variable
|
803 |
+
|
804 |
+
### Bug Fixes:
|
805 |
+
* fix for catch errors when retrieving extension index #11290
|
806 |
+
* fix very slow loading speed of .safetensors files when reading from network drives
|
807 |
+
* API cache cleanup
|
808 |
+
* fix UnicodeEncodeError when writing to file CLIP Interrogator batch mode
|
809 |
+
* fix warning of 'has_mps' deprecated from PyTorch
|
810 |
+
* fix problem with extra network saving images as previews losing generation info
|
811 |
+
* fix throwing exception when trying to resize image with I;16 mode
|
812 |
+
* fix for #11534: canvas zoom and pan extension hijacking shortcut keys
|
813 |
+
* fixed launch script to be runnable from any directory
|
814 |
+
* don't add "Seed Resize: -1x-1" to API image metadata
|
815 |
+
* correctly remove end parenthesis with ctrl+up/down
|
816 |
+
* fixing --subpath on newer gradio version
|
817 |
+
* fix: check fill size none zero when resize (fixes #11425)
|
818 |
+
* use submit and blur for quick settings textbox
|
819 |
+
* save img2img batch with images.save_image()
|
820 |
+
* prevent running preload.py for disabled extensions
|
821 |
+
* fix: previously, model name was added together with directory name to infotext and to [model_name] filename pattern; directory name is now not included
|
822 |
+
|
823 |
+
|
824 |
+
## 1.4.1
|
825 |
+
|
826 |
+
### Bug Fixes:
|
827 |
+
* add queue lock for refresh-checkpoints
|
828 |
+
|
829 |
+
## 1.4.0
|
830 |
+
|
831 |
+
### Features:
|
832 |
+
* zoom controls for inpainting
|
833 |
+
* run basic torch calculation at startup in parallel to reduce the performance impact of first generation
|
834 |
+
* option to pad prompt/neg prompt to be same length
|
835 |
+
* remove taming_transformers dependency
|
836 |
+
* custom k-diffusion scheduler settings
|
837 |
+
* add an option to show selected settings in main txt2img/img2img UI
|
838 |
+
* sysinfo tab in settings
|
839 |
+
* infer styles from prompts when pasting params into the UI
|
840 |
+
* an option to control the behavior of the above
|
841 |
+
|
842 |
+
### Minor:
|
843 |
+
* bump Gradio to 3.32.0
|
844 |
+
* bump xformers to 0.0.20
|
845 |
+
* Add option to disable token counters
|
846 |
+
* tooltip fixes & optimizations
|
847 |
+
* make it possible to configure filename for the zip download
|
848 |
+
* `[vae_filename]` pattern for filenames
|
849 |
+
* Revert discarding penultimate sigma for DPM-Solver++(2M) SDE
|
850 |
+
* change UI reorder setting to multiselect
|
851 |
+
* read version info form CHANGELOG.md if git version info is not available
|
852 |
+
* link footer API to Wiki when API is not active
|
853 |
+
* persistent conds cache (opt-in optimization)
|
854 |
+
|
855 |
+
### Extensions:
|
856 |
+
* After installing extensions, webui properly restarts the process rather than reloads the UI
|
857 |
+
* Added VAE listing to web API. Via: /sdapi/v1/sd-vae
|
858 |
+
* custom unet support
|
859 |
+
* Add onAfterUiUpdate callback
|
860 |
+
* refactor EmbeddingDatabase.register_embedding() to allow unregistering
|
861 |
+
* add before_process callback for scripts
|
862 |
+
* add ability for alwayson scripts to specify section and let user reorder those sections
|
863 |
+
|
864 |
+
### Bug Fixes:
|
865 |
+
* Fix dragging text to prompt
|
866 |
+
* fix incorrect quoting for infotext values with colon in them
|
867 |
+
* fix "hires. fix" prompt sharing same labels with txt2img_prompt
|
868 |
+
* Fix s_min_uncond default type int
|
869 |
+
* Fix for #10643 (Inpainting mask sometimes not working)
|
870 |
+
* fix bad styling for thumbs view in extra networks #10639
|
871 |
+
* fix for empty list of optimizations #10605
|
872 |
+
* small fixes to prepare_tcmalloc for Debian/Ubuntu compatibility
|
873 |
+
* fix --ui-debug-mode exit
|
874 |
+
* patch GitPython to not use leaky persistent processes
|
875 |
+
* fix duplicate Cross attention optimization after UI reload
|
876 |
+
* torch.cuda.is_available() check for SdOptimizationXformers
|
877 |
+
* fix hires fix using wrong conds in second pass if using Loras.
|
878 |
+
* handle exception when parsing generation parameters from png info
|
879 |
+
* fix upcast attention dtype error
|
880 |
+
* forcing Torch Version to 1.13.1 for RX 5000 series GPUs
|
881 |
+
* split mask blur into X and Y components, patch Outpainting MK2 accordingly
|
882 |
+
* don't die when a LoRA is a broken symlink
|
883 |
+
* allow activation of Generate Forever during generation
|
884 |
+
|
885 |
+
|
886 |
+
## 1.3.2
|
887 |
+
|
888 |
+
### Bug Fixes:
|
889 |
+
* fix files served out of tmp directory even if they are saved to disk
|
890 |
+
* fix postprocessing overwriting parameters
|
891 |
+
|
892 |
+
## 1.3.1
|
893 |
+
|
894 |
+
### Features:
|
895 |
+
* revert default cross attention optimization to Doggettx
|
896 |
+
|
897 |
+
### Bug Fixes:
|
898 |
+
* fix bug: LoRA don't apply on dropdown list sd_lora
|
899 |
+
* fix png info always added even if setting is not enabled
|
900 |
+
* fix some fields not applying in xyz plot
|
901 |
+
* fix "hires. fix" prompt sharing same labels with txt2img_prompt
|
902 |
+
* fix lora hashes not being added properly to infotex if there is only one lora
|
903 |
+
* fix --use-cpu failing to work properly at startup
|
904 |
+
* make --disable-opt-split-attention command line option work again
|
905 |
+
|
906 |
+
## 1.3.0
|
907 |
+
|
908 |
+
### Features:
|
909 |
+
* add UI to edit defaults
|
910 |
+
* token merging (via dbolya/tomesd)
|
911 |
+
* settings tab rework: add a lot of additional explanations and links
|
912 |
+
* load extensions' Git metadata in parallel to loading the main program to save a ton of time during startup
|
913 |
+
* update extensions table: show branch, show date in separate column, and show version from tags if available
|
914 |
+
* TAESD - another option for cheap live previews
|
915 |
+
* allow choosing sampler and prompts for second pass of hires fix - hidden by default, enabled in settings
|
916 |
+
* calculate hashes for Lora
|
917 |
+
* add lora hashes to infotext
|
918 |
+
* when pasting infotext, use infotext's lora hashes to find local loras for `<lora:xxx:1>` entries whose hashes match loras the user has
|
919 |
+
* select cross attention optimization from UI
|
920 |
+
|
921 |
+
### Minor:
|
922 |
+
* bump Gradio to 3.31.0
|
923 |
+
* bump PyTorch to 2.0.1 for macOS and Linux AMD
|
924 |
+
* allow setting defaults for elements in extensions' tabs
|
925 |
+
* allow selecting file type for live previews
|
926 |
+
* show "Loading..." for extra networks when displaying for the first time
|
927 |
+
* suppress ENSD infotext for samplers that don't use it
|
928 |
+
* clientside optimizations
|
929 |
+
* add options to show/hide hidden files and dirs in extra networks, and to not list models/files in hidden directories
|
930 |
+
* allow whitespace in styles.csv
|
931 |
+
* add option to reorder tabs
|
932 |
+
* move some functionality (swap resolution and set seed to -1) to client
|
933 |
+
* option to specify editor height for img2img
|
934 |
+
* button to copy image resolution into img2img width/height sliders
|
935 |
+
* switch from pyngrok to ngrok-py
|
936 |
+
* lazy-load images in extra networks UI
|
937 |
+
* set "Navigate image viewer with gamepad" option to false by default, by request
|
938 |
+
* change upscalers to download models into user-specified directory (from commandline args) rather than the default models/<...>
|
939 |
+
* allow hiding buttons in ui-config.json
|
940 |
+
|
941 |
+
### Extensions:
|
942 |
+
* add /sdapi/v1/script-info api
|
943 |
+
* use Ruff to lint Python code
|
944 |
+
* use ESlint to lint Javascript code
|
945 |
+
* add/modify CFG callbacks for Self-Attention Guidance extension
|
946 |
+
* add command and endpoint for graceful server stopping
|
947 |
+
* add some locals (prompts/seeds/etc) from processing function into the Processing class as fields
|
948 |
+
* rework quoting for infotext items that have commas in them to use JSON (should be backwards compatible except for cases where it didn't work previously)
|
949 |
+
* add /sdapi/v1/refresh-loras api checkpoint post request
|
950 |
+
* tests overhaul
|
951 |
+
|
952 |
+
### Bug Fixes:
|
953 |
+
* fix an issue preventing the program from starting if the user specifies a bad Gradio theme
|
954 |
+
* fix broken prompts from file script
|
955 |
+
* fix symlink scanning for extra networks
|
956 |
+
* fix --data-dir ignored when launching via webui-user.bat COMMANDLINE_ARGS
|
957 |
+
* allow web UI to be ran fully offline
|
958 |
+
* fix inability to run with --freeze-settings
|
959 |
+
* fix inability to merge checkpoint without adding metadata
|
960 |
+
* fix extra networks' save preview image not adding infotext for jpeg/webm
|
961 |
+
* remove blinking effect from text in hires fix and scale resolution preview
|
962 |
+
* make links to `http://<...>.git` extensions work in the extension tab
|
963 |
+
* fix bug with webui hanging at startup due to hanging git process
|
964 |
+
|
965 |
+
|
966 |
+
## 1.2.1
|
967 |
+
|
968 |
+
### Features:
|
969 |
+
* add an option to always refer to LoRA by filenames
|
970 |
+
|
971 |
+
### Bug Fixes:
|
972 |
+
* never refer to LoRA by an alias if multiple LoRAs have same alias or the alias is called none
|
973 |
+
* fix upscalers disappearing after the user reloads UI
|
974 |
+
* allow bf16 in safe unpickler (resolves problems with loading some LoRAs)
|
975 |
+
* allow web UI to be ran fully offline
|
976 |
+
* fix localizations not working
|
977 |
+
* fix error for LoRAs: `'LatentDiffusion' object has no attribute 'lora_layer_mapping'`
|
978 |
+
|
979 |
+
## 1.2.0
|
980 |
+
|
981 |
+
### Features:
|
982 |
+
* do not wait for Stable Diffusion model to load at startup
|
983 |
+
* add filename patterns: `[denoising]`
|
984 |
+
* directory hiding for extra networks: dirs starting with `.` will hide their cards on extra network tabs unless specifically searched for
|
985 |
+
* LoRA: for the `<...>` text in prompt, use name of LoRA that is in the metadata of the file, if present, instead of filename (both can be used to activate LoRA)
|
986 |
+
* LoRA: read infotext params from kohya-ss's extension parameters if they are present and if his extension is not active
|
987 |
+
* LoRA: fix some LoRAs not working (ones that have 3x3 convolution layer)
|
988 |
+
* LoRA: add an option to use old method of applying LoRAs (producing same results as with kohya-ss)
|
989 |
+
* add version to infotext, footer and console output when starting
|
990 |
+
* add links to wiki for filename pattern settings
|
991 |
+
* add extended info for quicksettings setting and use multiselect input instead of a text field
|
992 |
+
|
993 |
+
### Minor:
|
994 |
+
* bump Gradio to 3.29.0
|
995 |
+
* bump PyTorch to 2.0.1
|
996 |
+
* `--subpath` option for gradio for use with reverse proxy
|
997 |
+
* Linux/macOS: use existing virtualenv if already active (the VIRTUAL_ENV environment variable)
|
998 |
+
* do not apply localizations if there are none (possible frontend optimization)
|
999 |
+
* add extra `None` option for VAE in XYZ plot
|
1000 |
+
* print error to console when batch processing in img2img fails
|
1001 |
+
* create HTML for extra network pages only on demand
|
1002 |
+
* allow directories starting with `.` to still list their models for LoRA, checkpoints, etc
|
1003 |
+
* put infotext options into their own category in settings tab
|
1004 |
+
* do not show licenses page when user selects Show all pages in settings
|
1005 |
+
|
1006 |
+
### Extensions:
|
1007 |
+
* tooltip localization support
|
1008 |
+
* add API method to get LoRA models with prompt
|
1009 |
+
|
1010 |
+
### Bug Fixes:
|
1011 |
+
* re-add `/docs` endpoint
|
1012 |
+
* fix gamepad navigation
|
1013 |
+
* make the lightbox fullscreen image function properly
|
1014 |
+
* fix squished thumbnails in extras tab
|
1015 |
+
* keep "search" filter for extra networks when user refreshes the tab (previously it showed everything after you refreshed)
|
1016 |
+
* fix webui showing the same image if you configure the generation to always save results into same file
|
1017 |
+
* fix bug with upscalers not working properly
|
1018 |
+
* fix MPS on PyTorch 2.0.1, Intel Macs
|
1019 |
+
* make it so that custom context menu from contextMenu.js only disappears after user's click, ignoring non-user click events
|
1020 |
+
* prevent Reload UI button/link from reloading the page when it's not yet ready
|
1021 |
+
* fix prompts from file script failing to read contents from a drag/drop file
|
1022 |
+
|
1023 |
+
|
1024 |
+
## 1.1.1
|
1025 |
+
### Bug Fixes:
|
1026 |
+
* fix an error that prevents running webui on PyTorch<2.0 without --disable-safe-unpickle
|
1027 |
+
|
1028 |
+
## 1.1.0
|
1029 |
+
### Features:
|
1030 |
+
* switch to PyTorch 2.0.0 (except for AMD GPUs)
|
1031 |
+
* visual improvements to custom code scripts
|
1032 |
+
* add filename patterns: `[clip_skip]`, `[hasprompt<>]`, `[batch_number]`, `[generation_number]`
|
1033 |
+
* add support for saving init images in img2img, and record their hashes in infotext for reproducibility
|
1034 |
+
* automatically select current word when adjusting weight with ctrl+up/down
|
1035 |
+
* add dropdowns for X/Y/Z plot
|
1036 |
+
* add setting: Stable Diffusion/Random number generator source: makes it possible to make images generated from a given manual seed consistent across different GPUs
|
1037 |
+
* support Gradio's theme API
|
1038 |
+
* use TCMalloc on Linux by default; possible fix for memory leaks
|
1039 |
+
* add optimization option to remove negative conditioning at low sigma values #9177
|
1040 |
+
* embed model merge metadata in .safetensors file
|
1041 |
+
* extension settings backup/restore feature #9169
|
1042 |
+
* add "resize by" and "resize to" tabs to img2img
|
1043 |
+
* add option "keep original size" to textual inversion images preprocess
|
1044 |
+
* image viewer scrolling via analog stick
|
1045 |
+
* button to restore the progress from session lost / tab reload
|
1046 |
+
|
1047 |
+
### Minor:
|
1048 |
+
* bump Gradio to 3.28.1
|
1049 |
+
* change "scale to" to sliders in Extras tab
|
1050 |
+
* add labels to tool buttons to make it possible to hide them
|
1051 |
+
* add tiled inference support for ScuNET
|
1052 |
+
* add branch support for extension installation
|
1053 |
+
* change Linux installation script to install into current directory rather than `/home/username`
|
1054 |
+
* sort textual inversion embeddings by name (case-insensitive)
|
1055 |
+
* allow styles.csv to be symlinked or mounted in docker
|
1056 |
+
* remove the "do not add watermark to images" option
|
1057 |
+
* make selected tab configurable with UI config
|
1058 |
+
* make the extra networks UI fixed height and scrollable
|
1059 |
+
* add `disable_tls_verify` arg for use with self-signed certs
|
1060 |
+
|
1061 |
+
### Extensions:
|
1062 |
+
* add reload callback
|
1063 |
+
* add `is_hr_pass` field for processing
|
1064 |
+
|
1065 |
+
### Bug Fixes:
|
1066 |
+
* fix broken batch image processing on 'Extras/Batch Process' tab
|
1067 |
+
* add "None" option to extra networks dropdowns
|
1068 |
+
* fix FileExistsError for CLIP Interrogator
|
1069 |
+
* fix /sdapi/v1/txt2img endpoint not working on Linux #9319
|
1070 |
+
* fix disappearing live previews and progressbar during slow tasks
|
1071 |
+
* fix fullscreen image view not working properly in some cases
|
1072 |
+
* prevent alwayson_scripts args param resizing script_arg list when they are inserted in it
|
1073 |
+
* fix prompt schedule for second order samplers
|
1074 |
+
* fix image mask/composite for weird resolutions #9628
|
1075 |
+
* use correct images for previews when using AND (see #9491)
|
1076 |
+
* one broken image in img2img batch won't stop all processing
|
1077 |
+
* fix image orientation bug in train/preprocess
|
1078 |
+
* fix Ngrok recreating tunnels every reload
|
1079 |
+
* fix `--realesrgan-models-path` and `--ldsr-models-path` not working
|
1080 |
+
* fix `--skip-install` not working
|
1081 |
+
* use SAMPLE file format in Outpainting Mk2 & Poorman
|
1082 |
+
* do not fail all LoRAs if some have failed to load when making a picture
|
1083 |
+
|
1084 |
+
## 1.0.0
|
1085 |
+
* everything
|
CITATION.cff
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cff-version: 1.2.0
|
2 |
+
message: "If you use this software, please cite it as below."
|
3 |
+
authors:
|
4 |
+
- given-names: AUTOMATIC1111
|
5 |
+
title: "Stable Diffusion Web UI"
|
6 |
+
date-released: 2022-08-22
|
7 |
+
url: "https://github.com/AUTOMATIC1111/stable-diffusion-webui"
|
CODEOWNERS
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
* @AUTOMATIC1111
|
2 |
+
|
3 |
+
# if you were managing a localization and were removed from this file, this is because
|
4 |
+
# the intended way to do localizations now is via extensions. See:
|
5 |
+
# https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Developing-extensions
|
6 |
+
# Make a repo with your localization and since you are still listed as a collaborator
|
7 |
+
# you can add it to the wiki page yourself. This change is because some people complained
|
8 |
+
# the git commit log is cluttered with things unrelated to almost everyone and
|
9 |
+
# because I believe this is the best overall for the project to handle localizations almost
|
10 |
+
# entirely without my oversight.
|
11 |
+
|
12 |
+
|
LICENSE.txt
ADDED
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (c) 2023 AUTOMATIC1111
|
5 |
+
|
6 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
7 |
+
Everyone is permitted to copy and distribute verbatim copies
|
8 |
+
of this license document, but changing it is not allowed.
|
9 |
+
|
10 |
+
Preamble
|
11 |
+
|
12 |
+
The GNU Affero General Public License is a free, copyleft license for
|
13 |
+
software and other kinds of works, specifically designed to ensure
|
14 |
+
cooperation with the community in the case of network server software.
|
15 |
+
|
16 |
+
The licenses for most software and other practical works are designed
|
17 |
+
to take away your freedom to share and change the works. By contrast,
|
18 |
+
our General Public Licenses are intended to guarantee your freedom to
|
19 |
+
share and change all versions of a program--to make sure it remains free
|
20 |
+
software for all its users.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
Developers that use our General Public Licenses protect your rights
|
30 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
31 |
+
you this License which gives you legal permission to copy, distribute
|
32 |
+
and/or modify the software.
|
33 |
+
|
34 |
+
A secondary benefit of defending all users' freedom is that
|
35 |
+
improvements made in alternate versions of the program, if they
|
36 |
+
receive widespread use, become available for other developers to
|
37 |
+
incorporate. Many developers of free software are heartened and
|
38 |
+
encouraged by the resulting cooperation. However, in the case of
|
39 |
+
software used on network servers, this result may fail to come about.
|
40 |
+
The GNU General Public License permits making a modified version and
|
41 |
+
letting the public access it on a server without ever releasing its
|
42 |
+
source code to the public.
|
43 |
+
|
44 |
+
The GNU Affero General Public License is designed specifically to
|
45 |
+
ensure that, in such cases, the modified source code becomes available
|
46 |
+
to the community. It requires the operator of a network server to
|
47 |
+
provide the source code of the modified version running there to the
|
48 |
+
users of that server. Therefore, public use of a modified version, on
|
49 |
+
a publicly accessible server, gives the public access to the source
|
50 |
+
code of the modified version.
|
51 |
+
|
52 |
+
An older license, called the Affero General Public License and
|
53 |
+
published by Affero, was designed to accomplish similar goals. This is
|
54 |
+
a different license, not a version of the Affero GPL, but Affero has
|
55 |
+
released a new version of the Affero GPL which permits relicensing under
|
56 |
+
this license.
|
57 |
+
|
58 |
+
The precise terms and conditions for copying, distribution and
|
59 |
+
modification follow.
|
60 |
+
|
61 |
+
TERMS AND CONDITIONS
|
62 |
+
|
63 |
+
0. Definitions.
|
64 |
+
|
65 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
66 |
+
|
67 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
68 |
+
works, such as semiconductor masks.
|
69 |
+
|
70 |
+
"The Program" refers to any copyrightable work licensed under this
|
71 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
72 |
+
"recipients" may be individuals or organizations.
|
73 |
+
|
74 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
75 |
+
in a fashion requiring copyright permission, other than the making of an
|
76 |
+
exact copy. The resulting work is called a "modified version" of the
|
77 |
+
earlier work or a work "based on" the earlier work.
|
78 |
+
|
79 |
+
A "covered work" means either the unmodified Program or a work based
|
80 |
+
on the Program.
|
81 |
+
|
82 |
+
To "propagate" a work means to do anything with it that, without
|
83 |
+
permission, would make you directly or secondarily liable for
|
84 |
+
infringement under applicable copyright law, except executing it on a
|
85 |
+
computer or modifying a private copy. Propagation includes copying,
|
86 |
+
distribution (with or without modification), making available to the
|
87 |
+
public, and in some countries other activities as well.
|
88 |
+
|
89 |
+
To "convey" a work means any kind of propagation that enables other
|
90 |
+
parties to make or receive copies. Mere interaction with a user through
|
91 |
+
a computer network, with no transfer of a copy, is not conveying.
|
92 |
+
|
93 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
94 |
+
to the extent that it includes a convenient and prominently visible
|
95 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
96 |
+
tells the user that there is no warranty for the work (except to the
|
97 |
+
extent that warranties are provided), that licensees may convey the
|
98 |
+
work under this License, and how to view a copy of this License. If
|
99 |
+
the interface presents a list of user commands or options, such as a
|
100 |
+
menu, a prominent item in the list meets this criterion.
|
101 |
+
|
102 |
+
1. Source Code.
|
103 |
+
|
104 |
+
The "source code" for a work means the preferred form of the work
|
105 |
+
for making modifications to it. "Object code" means any non-source
|
106 |
+
form of a work.
|
107 |
+
|
108 |
+
A "Standard Interface" means an interface that either is an official
|
109 |
+
standard defined by a recognized standards body, or, in the case of
|
110 |
+
interfaces specified for a particular programming language, one that
|
111 |
+
is widely used among developers working in that language.
|
112 |
+
|
113 |
+
The "System Libraries" of an executable work include anything, other
|
114 |
+
than the work as a whole, that (a) is included in the normal form of
|
115 |
+
packaging a Major Component, but which is not part of that Major
|
116 |
+
Component, and (b) serves only to enable use of the work with that
|
117 |
+
Major Component, or to implement a Standard Interface for which an
|
118 |
+
implementation is available to the public in source code form. A
|
119 |
+
"Major Component", in this context, means a major essential component
|
120 |
+
(kernel, window system, and so on) of the specific operating system
|
121 |
+
(if any) on which the executable work runs, or a compiler used to
|
122 |
+
produce the work, or an object code interpreter used to run it.
|
123 |
+
|
124 |
+
The "Corresponding Source" for a work in object code form means all
|
125 |
+
the source code needed to generate, install, and (for an executable
|
126 |
+
work) run the object code and to modify the work, including scripts to
|
127 |
+
control those activities. However, it does not include the work's
|
128 |
+
System Libraries, or general-purpose tools or generally available free
|
129 |
+
programs which are used unmodified in performing those activities but
|
130 |
+
which are not part of the work. For example, Corresponding Source
|
131 |
+
includes interface definition files associated with source files for
|
132 |
+
the work, and the source code for shared libraries and dynamically
|
133 |
+
linked subprograms that the work is specifically designed to require,
|
134 |
+
such as by intimate data communication or control flow between those
|
135 |
+
subprograms and other parts of the work.
|
136 |
+
|
137 |
+
The Corresponding Source need not include anything that users
|
138 |
+
can regenerate automatically from other parts of the Corresponding
|
139 |
+
Source.
|
140 |
+
|
141 |
+
The Corresponding Source for a work in source code form is that
|
142 |
+
same work.
|
143 |
+
|
144 |
+
2. Basic Permissions.
|
145 |
+
|
146 |
+
All rights granted under this License are granted for the term of
|
147 |
+
copyright on the Program, and are irrevocable provided the stated
|
148 |
+
conditions are met. This License explicitly affirms your unlimited
|
149 |
+
permission to run the unmodified Program. The output from running a
|
150 |
+
covered work is covered by this License only if the output, given its
|
151 |
+
content, constitutes a covered work. This License acknowledges your
|
152 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
153 |
+
|
154 |
+
You may make, run and propagate covered works that you do not
|
155 |
+
convey, without conditions so long as your license otherwise remains
|
156 |
+
in force. You may convey covered works to others for the sole purpose
|
157 |
+
of having them make modifications exclusively for you, or provide you
|
158 |
+
with facilities for running those works, provided that you comply with
|
159 |
+
the terms of this License in conveying all material for which you do
|
160 |
+
not control copyright. Those thus making or running the covered works
|
161 |
+
for you must do so exclusively on your behalf, under your direction
|
162 |
+
and control, on terms that prohibit them from making any copies of
|
163 |
+
your copyrighted material outside their relationship with you.
|
164 |
+
|
165 |
+
Conveying under any other circumstances is permitted solely under
|
166 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
167 |
+
makes it unnecessary.
|
168 |
+
|
169 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
170 |
+
|
171 |
+
No covered work shall be deemed part of an effective technological
|
172 |
+
measure under any applicable law fulfilling obligations under article
|
173 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
174 |
+
similar laws prohibiting or restricting circumvention of such
|
175 |
+
measures.
|
176 |
+
|
177 |
+
When you convey a covered work, you waive any legal power to forbid
|
178 |
+
circumvention of technological measures to the extent such circumvention
|
179 |
+
is effected by exercising rights under this License with respect to
|
180 |
+
the covered work, and you disclaim any intention to limit operation or
|
181 |
+
modification of the work as a means of enforcing, against the work's
|
182 |
+
users, your or third parties' legal rights to forbid circumvention of
|
183 |
+
technological measures.
|
184 |
+
|
185 |
+
4. Conveying Verbatim Copies.
|
186 |
+
|
187 |
+
You may convey verbatim copies of the Program's source code as you
|
188 |
+
receive it, in any medium, provided that you conspicuously and
|
189 |
+
appropriately publish on each copy an appropriate copyright notice;
|
190 |
+
keep intact all notices stating that this License and any
|
191 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
192 |
+
keep intact all notices of the absence of any warranty; and give all
|
193 |
+
recipients a copy of this License along with the Program.
|
194 |
+
|
195 |
+
You may charge any price or no price for each copy that you convey,
|
196 |
+
and you may offer support or warranty protection for a fee.
|
197 |
+
|
198 |
+
5. Conveying Modified Source Versions.
|
199 |
+
|
200 |
+
You may convey a work based on the Program, or the modifications to
|
201 |
+
produce it from the Program, in the form of source code under the
|
202 |
+
terms of section 4, provided that you also meet all of these conditions:
|
203 |
+
|
204 |
+
a) The work must carry prominent notices stating that you modified
|
205 |
+
it, and giving a relevant date.
|
206 |
+
|
207 |
+
b) The work must carry prominent notices stating that it is
|
208 |
+
released under this License and any conditions added under section
|
209 |
+
7. This requirement modifies the requirement in section 4 to
|
210 |
+
"keep intact all notices".
|
211 |
+
|
212 |
+
c) You must license the entire work, as a whole, under this
|
213 |
+
License to anyone who comes into possession of a copy. This
|
214 |
+
License will therefore apply, along with any applicable section 7
|
215 |
+
additional terms, to the whole of the work, and all its parts,
|
216 |
+
regardless of how they are packaged. This License gives no
|
217 |
+
permission to license the work in any other way, but it does not
|
218 |
+
invalidate such permission if you have separately received it.
|
219 |
+
|
220 |
+
d) If the work has interactive user interfaces, each must display
|
221 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
222 |
+
interfaces that do not display Appropriate Legal Notices, your
|
223 |
+
work need not make them do so.
|
224 |
+
|
225 |
+
A compilation of a covered work with other separate and independent
|
226 |
+
works, which are not by their nature extensions of the covered work,
|
227 |
+
and which are not combined with it such as to form a larger program,
|
228 |
+
in or on a volume of a storage or distribution medium, is called an
|
229 |
+
"aggregate" if the compilation and its resulting copyright are not
|
230 |
+
used to limit the access or legal rights of the compilation's users
|
231 |
+
beyond what the individual works permit. Inclusion of a covered work
|
232 |
+
in an aggregate does not cause this License to apply to the other
|
233 |
+
parts of the aggregate.
|
234 |
+
|
235 |
+
6. Conveying Non-Source Forms.
|
236 |
+
|
237 |
+
You may convey a covered work in object code form under the terms
|
238 |
+
of sections 4 and 5, provided that you also convey the
|
239 |
+
machine-readable Corresponding Source under the terms of this License,
|
240 |
+
in one of these ways:
|
241 |
+
|
242 |
+
a) Convey the object code in, or embodied in, a physical product
|
243 |
+
(including a physical distribution medium), accompanied by the
|
244 |
+
Corresponding Source fixed on a durable physical medium
|
245 |
+
customarily used for software interchange.
|
246 |
+
|
247 |
+
b) Convey the object code in, or embodied in, a physical product
|
248 |
+
(including a physical distribution medium), accompanied by a
|
249 |
+
written offer, valid for at least three years and valid for as
|
250 |
+
long as you offer spare parts or customer support for that product
|
251 |
+
model, to give anyone who possesses the object code either (1) a
|
252 |
+
copy of the Corresponding Source for all the software in the
|
253 |
+
product that is covered by this License, on a durable physical
|
254 |
+
medium customarily used for software interchange, for a price no
|
255 |
+
more than your reasonable cost of physically performing this
|
256 |
+
conveying of source, or (2) access to copy the
|
257 |
+
Corresponding Source from a network server at no charge.
|
258 |
+
|
259 |
+
c) Convey individual copies of the object code with a copy of the
|
260 |
+
written offer to provide the Corresponding Source. This
|
261 |
+
alternative is allowed only occasionally and noncommercially, and
|
262 |
+
only if you received the object code with such an offer, in accord
|
263 |
+
with subsection 6b.
|
264 |
+
|
265 |
+
d) Convey the object code by offering access from a designated
|
266 |
+
place (gratis or for a charge), and offer equivalent access to the
|
267 |
+
Corresponding Source in the same way through the same place at no
|
268 |
+
further charge. You need not require recipients to copy the
|
269 |
+
Corresponding Source along with the object code. If the place to
|
270 |
+
copy the object code is a network server, the Corresponding Source
|
271 |
+
may be on a different server (operated by you or a third party)
|
272 |
+
that supports equivalent copying facilities, provided you maintain
|
273 |
+
clear directions next to the object code saying where to find the
|
274 |
+
Corresponding Source. Regardless of what server hosts the
|
275 |
+
Corresponding Source, you remain obligated to ensure that it is
|
276 |
+
available for as long as needed to satisfy these requirements.
|
277 |
+
|
278 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
279 |
+
you inform other peers where the object code and Corresponding
|
280 |
+
Source of the work are being offered to the general public at no
|
281 |
+
charge under subsection 6d.
|
282 |
+
|
283 |
+
A separable portion of the object code, whose source code is excluded
|
284 |
+
from the Corresponding Source as a System Library, need not be
|
285 |
+
included in conveying the object code work.
|
286 |
+
|
287 |
+
A "User Product" is either (1) a "consumer product", which means any
|
288 |
+
tangible personal property which is normally used for personal, family,
|
289 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
290 |
+
into a dwelling. In determining whether a product is a consumer product,
|
291 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
292 |
+
product received by a particular user, "normally used" refers to a
|
293 |
+
typical or common use of that class of product, regardless of the status
|
294 |
+
of the particular user or of the way in which the particular user
|
295 |
+
actually uses, or expects or is expected to use, the product. A product
|
296 |
+
is a consumer product regardless of whether the product has substantial
|
297 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
298 |
+
the only significant mode of use of the product.
|
299 |
+
|
300 |
+
"Installation Information" for a User Product means any methods,
|
301 |
+
procedures, authorization keys, or other information required to install
|
302 |
+
and execute modified versions of a covered work in that User Product from
|
303 |
+
a modified version of its Corresponding Source. The information must
|
304 |
+
suffice to ensure that the continued functioning of the modified object
|
305 |
+
code is in no case prevented or interfered with solely because
|
306 |
+
modification has been made.
|
307 |
+
|
308 |
+
If you convey an object code work under this section in, or with, or
|
309 |
+
specifically for use in, a User Product, and the conveying occurs as
|
310 |
+
part of a transaction in which the right of possession and use of the
|
311 |
+
User Product is transferred to the recipient in perpetuity or for a
|
312 |
+
fixed term (regardless of how the transaction is characterized), the
|
313 |
+
Corresponding Source conveyed under this section must be accompanied
|
314 |
+
by the Installation Information. But this requirement does not apply
|
315 |
+
if neither you nor any third party retains the ability to install
|
316 |
+
modified object code on the User Product (for example, the work has
|
317 |
+
been installed in ROM).
|
318 |
+
|
319 |
+
The requirement to provide Installation Information does not include a
|
320 |
+
requirement to continue to provide support service, warranty, or updates
|
321 |
+
for a work that has been modified or installed by the recipient, or for
|
322 |
+
the User Product in which it has been modified or installed. Access to a
|
323 |
+
network may be denied when the modification itself materially and
|
324 |
+
adversely affects the operation of the network or violates the rules and
|
325 |
+
protocols for communication across the network.
|
326 |
+
|
327 |
+
Corresponding Source conveyed, and Installation Information provided,
|
328 |
+
in accord with this section must be in a format that is publicly
|
329 |
+
documented (and with an implementation available to the public in
|
330 |
+
source code form), and must require no special password or key for
|
331 |
+
unpacking, reading or copying.
|
332 |
+
|
333 |
+
7. Additional Terms.
|
334 |
+
|
335 |
+
"Additional permissions" are terms that supplement the terms of this
|
336 |
+
License by making exceptions from one or more of its conditions.
|
337 |
+
Additional permissions that are applicable to the entire Program shall
|
338 |
+
be treated as though they were included in this License, to the extent
|
339 |
+
that they are valid under applicable law. If additional permissions
|
340 |
+
apply only to part of the Program, that part may be used separately
|
341 |
+
under those permissions, but the entire Program remains governed by
|
342 |
+
this License without regard to the additional permissions.
|
343 |
+
|
344 |
+
When you convey a copy of a covered work, you may at your option
|
345 |
+
remove any additional permissions from that copy, or from any part of
|
346 |
+
it. (Additional permissions may be written to require their own
|
347 |
+
removal in certain cases when you modify the work.) You may place
|
348 |
+
additional permissions on material, added by you to a covered work,
|
349 |
+
for which you have or can give appropriate copyright permission.
|
350 |
+
|
351 |
+
Notwithstanding any other provision of this License, for material you
|
352 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
353 |
+
that material) supplement the terms of this License with terms:
|
354 |
+
|
355 |
+
a) Disclaiming warranty or limiting liability differently from the
|
356 |
+
terms of sections 15 and 16 of this License; or
|
357 |
+
|
358 |
+
b) Requiring preservation of specified reasonable legal notices or
|
359 |
+
author attributions in that material or in the Appropriate Legal
|
360 |
+
Notices displayed by works containing it; or
|
361 |
+
|
362 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
363 |
+
requiring that modified versions of such material be marked in
|
364 |
+
reasonable ways as different from the original version; or
|
365 |
+
|
366 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
367 |
+
authors of the material; or
|
368 |
+
|
369 |
+
e) Declining to grant rights under trademark law for use of some
|
370 |
+
trade names, trademarks, or service marks; or
|
371 |
+
|
372 |
+
f) Requiring indemnification of licensors and authors of that
|
373 |
+
material by anyone who conveys the material (or modified versions of
|
374 |
+
it) with contractual assumptions of liability to the recipient, for
|
375 |
+
any liability that these contractual assumptions directly impose on
|
376 |
+
those licensors and authors.
|
377 |
+
|
378 |
+
All other non-permissive additional terms are considered "further
|
379 |
+
restrictions" within the meaning of section 10. If the Program as you
|
380 |
+
received it, or any part of it, contains a notice stating that it is
|
381 |
+
governed by this License along with a term that is a further
|
382 |
+
restriction, you may remove that term. If a license document contains
|
383 |
+
a further restriction but permits relicensing or conveying under this
|
384 |
+
License, you may add to a covered work material governed by the terms
|
385 |
+
of that license document, provided that the further restriction does
|
386 |
+
not survive such relicensing or conveying.
|
387 |
+
|
388 |
+
If you add terms to a covered work in accord with this section, you
|
389 |
+
must place, in the relevant source files, a statement of the
|
390 |
+
additional terms that apply to those files, or a notice indicating
|
391 |
+
where to find the applicable terms.
|
392 |
+
|
393 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
394 |
+
form of a separately written license, or stated as exceptions;
|
395 |
+
the above requirements apply either way.
|
396 |
+
|
397 |
+
8. Termination.
|
398 |
+
|
399 |
+
You may not propagate or modify a covered work except as expressly
|
400 |
+
provided under this License. Any attempt otherwise to propagate or
|
401 |
+
modify it is void, and will automatically terminate your rights under
|
402 |
+
this License (including any patent licenses granted under the third
|
403 |
+
paragraph of section 11).
|
404 |
+
|
405 |
+
However, if you cease all violation of this License, then your
|
406 |
+
license from a particular copyright holder is reinstated (a)
|
407 |
+
provisionally, unless and until the copyright holder explicitly and
|
408 |
+
finally terminates your license, and (b) permanently, if the copyright
|
409 |
+
holder fails to notify you of the violation by some reasonable means
|
410 |
+
prior to 60 days after the cessation.
|
411 |
+
|
412 |
+
Moreover, your license from a particular copyright holder is
|
413 |
+
reinstated permanently if the copyright holder notifies you of the
|
414 |
+
violation by some reasonable means, this is the first time you have
|
415 |
+
received notice of violation of this License (for any work) from that
|
416 |
+
copyright holder, and you cure the violation prior to 30 days after
|
417 |
+
your receipt of the notice.
|
418 |
+
|
419 |
+
Termination of your rights under this section does not terminate the
|
420 |
+
licenses of parties who have received copies or rights from you under
|
421 |
+
this License. If your rights have been terminated and not permanently
|
422 |
+
reinstated, you do not qualify to receive new licenses for the same
|
423 |
+
material under section 10.
|
424 |
+
|
425 |
+
9. Acceptance Not Required for Having Copies.
|
426 |
+
|
427 |
+
You are not required to accept this License in order to receive or
|
428 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
429 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
430 |
+
to receive a copy likewise does not require acceptance. However,
|
431 |
+
nothing other than this License grants you permission to propagate or
|
432 |
+
modify any covered work. These actions infringe copyright if you do
|
433 |
+
not accept this License. Therefore, by modifying or propagating a
|
434 |
+
covered work, you indicate your acceptance of this License to do so.
|
435 |
+
|
436 |
+
10. Automatic Licensing of Downstream Recipients.
|
437 |
+
|
438 |
+
Each time you convey a covered work, the recipient automatically
|
439 |
+
receives a license from the original licensors, to run, modify and
|
440 |
+
propagate that work, subject to this License. You are not responsible
|
441 |
+
for enforcing compliance by third parties with this License.
|
442 |
+
|
443 |
+
An "entity transaction" is a transaction transferring control of an
|
444 |
+
organization, or substantially all assets of one, or subdividing an
|
445 |
+
organization, or merging organizations. If propagation of a covered
|
446 |
+
work results from an entity transaction, each party to that
|
447 |
+
transaction who receives a copy of the work also receives whatever
|
448 |
+
licenses to the work the party's predecessor in interest had or could
|
449 |
+
give under the previous paragraph, plus a right to possession of the
|
450 |
+
Corresponding Source of the work from the predecessor in interest, if
|
451 |
+
the predecessor has it or can get it with reasonable efforts.
|
452 |
+
|
453 |
+
You may not impose any further restrictions on the exercise of the
|
454 |
+
rights granted or affirmed under this License. For example, you may
|
455 |
+
not impose a license fee, royalty, or other charge for exercise of
|
456 |
+
rights granted under this License, and you may not initiate litigation
|
457 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
458 |
+
any patent claim is infringed by making, using, selling, offering for
|
459 |
+
sale, or importing the Program or any portion of it.
|
460 |
+
|
461 |
+
11. Patents.
|
462 |
+
|
463 |
+
A "contributor" is a copyright holder who authorizes use under this
|
464 |
+
License of the Program or a work on which the Program is based. The
|
465 |
+
work thus licensed is called the contributor's "contributor version".
|
466 |
+
|
467 |
+
A contributor's "essential patent claims" are all patent claims
|
468 |
+
owned or controlled by the contributor, whether already acquired or
|
469 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
470 |
+
by this License, of making, using, or selling its contributor version,
|
471 |
+
but do not include claims that would be infringed only as a
|
472 |
+
consequence of further modification of the contributor version. For
|
473 |
+
purposes of this definition, "control" includes the right to grant
|
474 |
+
patent sublicenses in a manner consistent with the requirements of
|
475 |
+
this License.
|
476 |
+
|
477 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
478 |
+
patent license under the contributor's essential patent claims, to
|
479 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
480 |
+
propagate the contents of its contributor version.
|
481 |
+
|
482 |
+
In the following three paragraphs, a "patent license" is any express
|
483 |
+
agreement or commitment, however denominated, not to enforce a patent
|
484 |
+
(such as an express permission to practice a patent or covenant not to
|
485 |
+
sue for patent infringement). To "grant" such a patent license to a
|
486 |
+
party means to make such an agreement or commitment not to enforce a
|
487 |
+
patent against the party.
|
488 |
+
|
489 |
+
If you convey a covered work, knowingly relying on a patent license,
|
490 |
+
and the Corresponding Source of the work is not available for anyone
|
491 |
+
to copy, free of charge and under the terms of this License, through a
|
492 |
+
publicly available network server or other readily accessible means,
|
493 |
+
then you must either (1) cause the Corresponding Source to be so
|
494 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
495 |
+
patent license for this particular work, or (3) arrange, in a manner
|
496 |
+
consistent with the requirements of this License, to extend the patent
|
497 |
+
license to downstream recipients. "Knowingly relying" means you have
|
498 |
+
actual knowledge that, but for the patent license, your conveying the
|
499 |
+
covered work in a country, or your recipient's use of the covered work
|
500 |
+
in a country, would infringe one or more identifiable patents in that
|
501 |
+
country that you have reason to believe are valid.
|
502 |
+
|
503 |
+
If, pursuant to or in connection with a single transaction or
|
504 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
505 |
+
covered work, and grant a patent license to some of the parties
|
506 |
+
receiving the covered work authorizing them to use, propagate, modify
|
507 |
+
or convey a specific copy of the covered work, then the patent license
|
508 |
+
you grant is automatically extended to all recipients of the covered
|
509 |
+
work and works based on it.
|
510 |
+
|
511 |
+
A patent license is "discriminatory" if it does not include within
|
512 |
+
the scope of its coverage, prohibits the exercise of, or is
|
513 |
+
conditioned on the non-exercise of one or more of the rights that are
|
514 |
+
specifically granted under this License. You may not convey a covered
|
515 |
+
work if you are a party to an arrangement with a third party that is
|
516 |
+
in the business of distributing software, under which you make payment
|
517 |
+
to the third party based on the extent of your activity of conveying
|
518 |
+
the work, and under which the third party grants, to any of the
|
519 |
+
parties who would receive the covered work from you, a discriminatory
|
520 |
+
patent license (a) in connection with copies of the covered work
|
521 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
522 |
+
for and in connection with specific products or compilations that
|
523 |
+
contain the covered work, unless you entered into that arrangement,
|
524 |
+
or that patent license was granted, prior to 28 March 2007.
|
525 |
+
|
526 |
+
Nothing in this License shall be construed as excluding or limiting
|
527 |
+
any implied license or other defenses to infringement that may
|
528 |
+
otherwise be available to you under applicable patent law.
|
529 |
+
|
530 |
+
12. No Surrender of Others' Freedom.
|
531 |
+
|
532 |
+
If conditions are imposed on you (whether by court order, agreement or
|
533 |
+
otherwise) that contradict the conditions of this License, they do not
|
534 |
+
excuse you from the conditions of this License. If you cannot convey a
|
535 |
+
covered work so as to satisfy simultaneously your obligations under this
|
536 |
+
License and any other pertinent obligations, then as a consequence you may
|
537 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
538 |
+
to collect a royalty for further conveying from those to whom you convey
|
539 |
+
the Program, the only way you could satisfy both those terms and this
|
540 |
+
License would be to refrain entirely from conveying the Program.
|
541 |
+
|
542 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
543 |
+
|
544 |
+
Notwithstanding any other provision of this License, if you modify the
|
545 |
+
Program, your modified version must prominently offer all users
|
546 |
+
interacting with it remotely through a computer network (if your version
|
547 |
+
supports such interaction) an opportunity to receive the Corresponding
|
548 |
+
Source of your version by providing access to the Corresponding Source
|
549 |
+
from a network server at no charge, through some standard or customary
|
550 |
+
means of facilitating copying of software. This Corresponding Source
|
551 |
+
shall include the Corresponding Source for any work covered by version 3
|
552 |
+
of the GNU General Public License that is incorporated pursuant to the
|
553 |
+
following paragraph.
|
554 |
+
|
555 |
+
Notwithstanding any other provision of this License, you have
|
556 |
+
permission to link or combine any covered work with a work licensed
|
557 |
+
under version 3 of the GNU General Public License into a single
|
558 |
+
combined work, and to convey the resulting work. The terms of this
|
559 |
+
License will continue to apply to the part which is the covered work,
|
560 |
+
but the work with which it is combined will remain governed by version
|
561 |
+
3 of the GNU General Public License.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU Affero General Public License from time to time. Such new versions
|
567 |
+
will be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU Affero General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU Affero General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU Affero General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU Affero General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If your software can interact with users remotely through a computer
|
653 |
+
network, you should also make sure that it provides a way for users to
|
654 |
+
get its source. For example, if your program is a web application, its
|
655 |
+
interface could display a "Source" link that leads users to an archive
|
656 |
+
of the code. There are many ways you could offer source, and different
|
657 |
+
solutions will be better for different programs; see section 13 for the
|
658 |
+
specific requirements.
|
659 |
+
|
660 |
+
You should also get your employer (if you work as a programmer) or school,
|
661 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
662 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
663 |
+
<https://www.gnu.org/licenses/>.
|
README.md
CHANGED
@@ -1,12 +1,211 @@
|
|
1 |
-
---
|
2 |
-
title:
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Ellas_SD
|
3 |
+
app_file: ./venv/bin/gradio
|
4 |
+
sdk: gradio
|
5 |
+
sdk_version: 3.41.2
|
6 |
+
---
|
7 |
+
# Stable Diffusion web UI
|
8 |
+
A web interface for Stable Diffusion, implemented using Gradio library.
|
9 |
+
|
10 |
+
![](screenshot.png)
|
11 |
+
|
12 |
+
## Features
|
13 |
+
[Detailed feature showcase with images](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features):
|
14 |
+
- Original txt2img and img2img modes
|
15 |
+
- One click install and run script (but you still must install python and git)
|
16 |
+
- Outpainting
|
17 |
+
- Inpainting
|
18 |
+
- Color Sketch
|
19 |
+
- Prompt Matrix
|
20 |
+
- Stable Diffusion Upscale
|
21 |
+
- Attention, specify parts of text that the model should pay more attention to
|
22 |
+
- a man in a `((tuxedo))` - will pay more attention to tuxedo
|
23 |
+
- a man in a `(tuxedo:1.21)` - alternative syntax
|
24 |
+
- select text and press `Ctrl+Up` or `Ctrl+Down` (or `Command+Up` or `Command+Down` if you're on a MacOS) to automatically adjust attention to selected text (code contributed by anonymous user)
|
25 |
+
- Loopback, run img2img processing multiple times
|
26 |
+
- X/Y/Z plot, a way to draw a 3 dimensional plot of images with different parameters
|
27 |
+
- Textual Inversion
|
28 |
+
- have as many embeddings as you want and use any names you like for them
|
29 |
+
- use multiple embeddings with different numbers of vectors per token
|
30 |
+
- works with half precision floating point numbers
|
31 |
+
- train embeddings on 8GB (also reports of 6GB working)
|
32 |
+
- Extras tab with:
|
33 |
+
- GFPGAN, neural network that fixes faces
|
34 |
+
- CodeFormer, face restoration tool as an alternative to GFPGAN
|
35 |
+
- RealESRGAN, neural network upscaler
|
36 |
+
- ESRGAN, neural network upscaler with a lot of third party models
|
37 |
+
- SwinIR and Swin2SR ([see here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/2092)), neural network upscalers
|
38 |
+
- LDSR, Latent diffusion super resolution upscaling
|
39 |
+
- Resizing aspect ratio options
|
40 |
+
- Sampling method selection
|
41 |
+
- Adjust sampler eta values (noise multiplier)
|
42 |
+
- More advanced noise setting options
|
43 |
+
- Interrupt processing at any time
|
44 |
+
- 4GB video card support (also reports of 2GB working)
|
45 |
+
- Correct seeds for batches
|
46 |
+
- Live prompt token length validation
|
47 |
+
- Generation parameters
|
48 |
+
- parameters you used to generate images are saved with that image
|
49 |
+
- in PNG chunks for PNG, in EXIF for JPEG
|
50 |
+
- can drag the image to PNG info tab to restore generation parameters and automatically copy them into UI
|
51 |
+
- can be disabled in settings
|
52 |
+
- drag and drop an image/text-parameters to promptbox
|
53 |
+
- Read Generation Parameters Button, loads parameters in promptbox to UI
|
54 |
+
- Settings page
|
55 |
+
- Running arbitrary python code from UI (must run with `--allow-code` to enable)
|
56 |
+
- Mouseover hints for most UI elements
|
57 |
+
- Possible to change defaults/mix/max/step values for UI elements via text config
|
58 |
+
- Tiling support, a checkbox to create images that can be tiled like textures
|
59 |
+
- Progress bar and live image generation preview
|
60 |
+
- Can use a separate neural network to produce previews with almost none VRAM or compute requirement
|
61 |
+
- Negative prompt, an extra text field that allows you to list what you don't want to see in generated image
|
62 |
+
- Styles, a way to save part of prompt and easily apply them via dropdown later
|
63 |
+
- Variations, a way to generate same image but with tiny differences
|
64 |
+
- Seed resizing, a way to generate same image but at slightly different resolution
|
65 |
+
- CLIP interrogator, a button that tries to guess prompt from an image
|
66 |
+
- Prompt Editing, a way to change prompt mid-generation, say to start making a watermelon and switch to anime girl midway
|
67 |
+
- Batch Processing, process a group of files using img2img
|
68 |
+
- Img2img Alternative, reverse Euler method of cross attention control
|
69 |
+
- Highres Fix, a convenience option to produce high resolution pictures in one click without usual distortions
|
70 |
+
- Reloading checkpoints on the fly
|
71 |
+
- Checkpoint Merger, a tab that allows you to merge up to 3 checkpoints into one
|
72 |
+
- [Custom scripts](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts) with many extensions from community
|
73 |
+
- [Composable-Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/), a way to use multiple prompts at once
|
74 |
+
- separate prompts using uppercase `AND`
|
75 |
+
- also supports weights for prompts: `a cat :1.2 AND a dog AND a penguin :2.2`
|
76 |
+
- No token limit for prompts (original stable diffusion lets you use up to 75 tokens)
|
77 |
+
- DeepDanbooru integration, creates danbooru style tags for anime prompts
|
78 |
+
- [xformers](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Xformers), major speed increase for select cards: (add `--xformers` to commandline args)
|
79 |
+
- via extension: [History tab](https://github.com/yfszzx/stable-diffusion-webui-images-browser): view, direct and delete images conveniently within the UI
|
80 |
+
- Generate forever option
|
81 |
+
- Training tab
|
82 |
+
- hypernetworks and embeddings options
|
83 |
+
- Preprocessing images: cropping, mirroring, autotagging using BLIP or deepdanbooru (for anime)
|
84 |
+
- Clip skip
|
85 |
+
- Hypernetworks
|
86 |
+
- Loras (same as Hypernetworks but more pretty)
|
87 |
+
- A separate UI where you can choose, with preview, which embeddings, hypernetworks or Loras to add to your prompt
|
88 |
+
- Can select to load a different VAE from settings screen
|
89 |
+
- Estimated completion time in progress bar
|
90 |
+
- API
|
91 |
+
- Support for dedicated [inpainting model](https://github.com/runwayml/stable-diffusion#inpainting-with-stable-diffusion) by RunwayML
|
92 |
+
- via extension: [Aesthetic Gradients](https://github.com/AUTOMATIC1111/stable-diffusion-webui-aesthetic-gradients), a way to generate images with a specific aesthetic by using clip images embeds (implementation of [https://github.com/vicgalle/stable-diffusion-aesthetic-gradients](https://github.com/vicgalle/stable-diffusion-aesthetic-gradients))
|
93 |
+
- [Stable Diffusion 2.0](https://github.com/Stability-AI/stablediffusion) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#stable-diffusion-20) for instructions
|
94 |
+
- [Alt-Diffusion](https://arxiv.org/abs/2211.06679) support - see [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#alt-diffusion) for instructions
|
95 |
+
- Now without any bad letters!
|
96 |
+
- Load checkpoints in safetensors format
|
97 |
+
- Eased resolution restriction: generated image's dimensions must be a multiple of 8 rather than 64
|
98 |
+
- Now with a license!
|
99 |
+
- Reorder elements in the UI from settings screen
|
100 |
+
- [Segmind Stable Diffusion](https://huggingface.co/segmind/SSD-1B) support
|
101 |
+
|
102 |
+
## Installation and Running
|
103 |
+
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for:
|
104 |
+
- [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended)
|
105 |
+
- [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
|
106 |
+
- [Intel CPUs, Intel GPUs (both integrated and discrete)](https://github.com/openvinotoolkit/stable-diffusion-webui/wiki/Installation-on-Intel-Silicon) (external wiki page)
|
107 |
+
- [Ascend NPUs](https://github.com/wangshuai09/stable-diffusion-webui/wiki/Install-and-run-on-Ascend-NPUs) (external wiki page)
|
108 |
+
|
109 |
+
Alternatively, use online services (like Google Colab):
|
110 |
+
|
111 |
+
- [List of Online Services](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services)
|
112 |
+
|
113 |
+
### Installation on Windows 10/11 with NVidia-GPUs using release package
|
114 |
+
1. Download `sd.webui.zip` from [v1.0.0-pre](https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases/tag/v1.0.0-pre) and extract its contents.
|
115 |
+
2. Run `update.bat`.
|
116 |
+
3. Run `run.bat`.
|
117 |
+
> For more details see [Install-and-Run-on-NVidia-GPUs](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs)
|
118 |
+
|
119 |
+
### Automatic Installation on Windows
|
120 |
+
1. Install [Python 3.10.6](https://www.python.org/downloads/release/python-3106/) (Newer version of Python does not support torch), checking "Add Python to PATH".
|
121 |
+
2. Install [git](https://git-scm.com/download/win).
|
122 |
+
3. Download the stable-diffusion-webui repository, for example by running `git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git`.
|
123 |
+
4. Run `webui-user.bat` from Windows Explorer as normal, non-administrator, user.
|
124 |
+
|
125 |
+
### Automatic Installation on Linux
|
126 |
+
1. Install the dependencies:
|
127 |
+
```bash
|
128 |
+
# Debian-based:
|
129 |
+
sudo apt install wget git python3 python3-venv libgl1 libglib2.0-0
|
130 |
+
# Red Hat-based:
|
131 |
+
sudo dnf install wget git python3 gperftools-libs libglvnd-glx
|
132 |
+
# openSUSE-based:
|
133 |
+
sudo zypper install wget git python3 libtcmalloc4 libglvnd
|
134 |
+
# Arch-based:
|
135 |
+
sudo pacman -S wget git python3
|
136 |
+
```
|
137 |
+
If your system is very new, you need to install python3.11 or python3.10:
|
138 |
+
```bash
|
139 |
+
# Ubuntu 24.04
|
140 |
+
sudo add-apt-repository ppa:deadsnakes/ppa
|
141 |
+
sudo apt update
|
142 |
+
sudo apt install python3.11
|
143 |
+
|
144 |
+
# Manjaro/Arch
|
145 |
+
sudo pacman -S yay
|
146 |
+
yay -S python311 # do not confuse with python3.11 package
|
147 |
+
|
148 |
+
# Only for 3.11
|
149 |
+
# Then set up env variable in launch script
|
150 |
+
export python_cmd="python3.11"
|
151 |
+
# or in webui-user.sh
|
152 |
+
python_cmd="python3.11"
|
153 |
+
```
|
154 |
+
2. Navigate to the directory you would like the webui to be installed and execute the following command:
|
155 |
+
```bash
|
156 |
+
wget -q https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/master/webui.sh
|
157 |
+
```
|
158 |
+
Or just clone the repo wherever you want:
|
159 |
+
```bash
|
160 |
+
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
|
161 |
+
```
|
162 |
+
|
163 |
+
3. Run `webui.sh`.
|
164 |
+
4. Check `webui-user.sh` for options.
|
165 |
+
### Installation on Apple Silicon
|
166 |
+
|
167 |
+
Find the instructions [here](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon).
|
168 |
+
|
169 |
+
## Contributing
|
170 |
+
Here's how to add code to this repo: [Contributing](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing)
|
171 |
+
|
172 |
+
## Documentation
|
173 |
+
|
174 |
+
The documentation was moved from this README over to the project's [wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
175 |
+
|
176 |
+
For the purposes of getting Google and other search engines to crawl the wiki, here's a link to the (not for humans) [crawlable wiki](https://github-wiki-see.page/m/AUTOMATIC1111/stable-diffusion-webui/wiki).
|
177 |
+
|
178 |
+
## Credits
|
179 |
+
Licenses for borrowed code can be found in `Settings -> Licenses` screen, and also in `html/licenses.html` file.
|
180 |
+
|
181 |
+
- Stable Diffusion - https://github.com/Stability-AI/stablediffusion, https://github.com/CompVis/taming-transformers, https://github.com/mcmonkey4eva/sd3-ref
|
182 |
+
- k-diffusion - https://github.com/crowsonkb/k-diffusion.git
|
183 |
+
- Spandrel - https://github.com/chaiNNer-org/spandrel implementing
|
184 |
+
- GFPGAN - https://github.com/TencentARC/GFPGAN.git
|
185 |
+
- CodeFormer - https://github.com/sczhou/CodeFormer
|
186 |
+
- ESRGAN - https://github.com/xinntao/ESRGAN
|
187 |
+
- SwinIR - https://github.com/JingyunLiang/SwinIR
|
188 |
+
- Swin2SR - https://github.com/mv-lab/swin2sr
|
189 |
+
- LDSR - https://github.com/Hafiidz/latent-diffusion
|
190 |
+
- MiDaS - https://github.com/isl-org/MiDaS
|
191 |
+
- Ideas for optimizations - https://github.com/basujindal/stable-diffusion
|
192 |
+
- Cross Attention layer optimization - Doggettx - https://github.com/Doggettx/stable-diffusion, original idea for prompt editing.
|
193 |
+
- Cross Attention layer optimization - InvokeAI, lstein - https://github.com/invoke-ai/InvokeAI (originally http://github.com/lstein/stable-diffusion)
|
194 |
+
- Sub-quadratic Cross Attention layer optimization - Alex Birch (https://github.com/Birch-san/diffusers/pull/1), Amin Rezaei (https://github.com/AminRezaei0x443/memory-efficient-attention)
|
195 |
+
- Textual Inversion - Rinon Gal - https://github.com/rinongal/textual_inversion (we're not using his code, but we are using his ideas).
|
196 |
+
- Idea for SD upscale - https://github.com/jquesnelle/txt2imghd
|
197 |
+
- Noise generation for outpainting mk2 - https://github.com/parlance-zz/g-diffuser-bot
|
198 |
+
- CLIP interrogator idea and borrowing some code - https://github.com/pharmapsychotic/clip-interrogator
|
199 |
+
- Idea for Composable Diffusion - https://github.com/energy-based-model/Compositional-Visual-Generation-with-Composable-Diffusion-Models-PyTorch
|
200 |
+
- xformers - https://github.com/facebookresearch/xformers
|
201 |
+
- DeepDanbooru - interrogator for anime diffusers https://github.com/KichangKim/DeepDanbooru
|
202 |
+
- Sampling in float32 precision from a float16 UNet - marunine for the idea, Birch-san for the example Diffusers implementation (https://github.com/Birch-san/diffusers-play/tree/92feee6)
|
203 |
+
- Instruct pix2pix - Tim Brooks (star), Aleksander Holynski (star), Alexei A. Efros (no star) - https://github.com/timothybrooks/instruct-pix2pix
|
204 |
+
- Security advice - RyotaK
|
205 |
+
- UniPC sampler - Wenliang Zhao - https://github.com/wl-zhao/UniPC
|
206 |
+
- TAESD - Ollin Boer Bohan - https://github.com/madebyollin/taesd
|
207 |
+
- LyCORIS - KohakuBlueleaf
|
208 |
+
- Restart sampling - lambertae - https://github.com/Newbeeer/diffusion_restart_sampling
|
209 |
+
- Hypertile - tfernd - https://github.com/tfernd/HyperTile
|
210 |
+
- Initial Gradio script - posted on 4chan by an Anonymous user. Thank you Anonymous user.
|
211 |
+
- (You)
|
_typos.toml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[default.extend-words]
|
2 |
+
# Part of "RGBa" (Pillow's pre-multiplied alpha RGB mode)
|
3 |
+
Ba = "Ba"
|
4 |
+
# HSA is something AMD uses for their GPUs
|
5 |
+
HSA = "HSA"
|
configs/alt-diffusion-inference.yaml
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
base_learning_rate: 1.0e-04
|
3 |
+
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
4 |
+
params:
|
5 |
+
linear_start: 0.00085
|
6 |
+
linear_end: 0.0120
|
7 |
+
num_timesteps_cond: 1
|
8 |
+
log_every_t: 200
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: "jpg"
|
11 |
+
cond_stage_key: "txt"
|
12 |
+
image_size: 64
|
13 |
+
channels: 4
|
14 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
15 |
+
conditioning_key: crossattn
|
16 |
+
monitor: val/loss_simple_ema
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: False
|
19 |
+
|
20 |
+
scheduler_config: # 10000 warmup steps
|
21 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
22 |
+
params:
|
23 |
+
warm_up_steps: [ 10000 ]
|
24 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
25 |
+
f_start: [ 1.e-6 ]
|
26 |
+
f_max: [ 1. ]
|
27 |
+
f_min: [ 1. ]
|
28 |
+
|
29 |
+
unet_config:
|
30 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
31 |
+
params:
|
32 |
+
image_size: 32 # unused
|
33 |
+
in_channels: 4
|
34 |
+
out_channels: 4
|
35 |
+
model_channels: 320
|
36 |
+
attention_resolutions: [ 4, 2, 1 ]
|
37 |
+
num_res_blocks: 2
|
38 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
39 |
+
num_heads: 8
|
40 |
+
use_spatial_transformer: True
|
41 |
+
transformer_depth: 1
|
42 |
+
context_dim: 768
|
43 |
+
use_checkpoint: False
|
44 |
+
legacy: False
|
45 |
+
|
46 |
+
first_stage_config:
|
47 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
48 |
+
params:
|
49 |
+
embed_dim: 4
|
50 |
+
monitor: val/rec_loss
|
51 |
+
ddconfig:
|
52 |
+
double_z: true
|
53 |
+
z_channels: 4
|
54 |
+
resolution: 256
|
55 |
+
in_channels: 3
|
56 |
+
out_ch: 3
|
57 |
+
ch: 128
|
58 |
+
ch_mult:
|
59 |
+
- 1
|
60 |
+
- 2
|
61 |
+
- 4
|
62 |
+
- 4
|
63 |
+
num_res_blocks: 2
|
64 |
+
attn_resolutions: []
|
65 |
+
dropout: 0.0
|
66 |
+
lossconfig:
|
67 |
+
target: torch.nn.Identity
|
68 |
+
|
69 |
+
cond_stage_config:
|
70 |
+
target: modules.xlmr.BertSeriesModelWithTransformation
|
71 |
+
params:
|
72 |
+
name: "XLMR-Large"
|
configs/alt-diffusion-m18-inference.yaml
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
base_learning_rate: 1.0e-04
|
3 |
+
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
4 |
+
params:
|
5 |
+
linear_start: 0.00085
|
6 |
+
linear_end: 0.0120
|
7 |
+
num_timesteps_cond: 1
|
8 |
+
log_every_t: 200
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: "jpg"
|
11 |
+
cond_stage_key: "txt"
|
12 |
+
image_size: 64
|
13 |
+
channels: 4
|
14 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
15 |
+
conditioning_key: crossattn
|
16 |
+
monitor: val/loss_simple_ema
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: False
|
19 |
+
|
20 |
+
scheduler_config: # 10000 warmup steps
|
21 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
22 |
+
params:
|
23 |
+
warm_up_steps: [ 10000 ]
|
24 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
25 |
+
f_start: [ 1.e-6 ]
|
26 |
+
f_max: [ 1. ]
|
27 |
+
f_min: [ 1. ]
|
28 |
+
|
29 |
+
unet_config:
|
30 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
31 |
+
params:
|
32 |
+
image_size: 32 # unused
|
33 |
+
in_channels: 4
|
34 |
+
out_channels: 4
|
35 |
+
model_channels: 320
|
36 |
+
attention_resolutions: [ 4, 2, 1 ]
|
37 |
+
num_res_blocks: 2
|
38 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
39 |
+
num_head_channels: 64
|
40 |
+
use_spatial_transformer: True
|
41 |
+
use_linear_in_transformer: True
|
42 |
+
transformer_depth: 1
|
43 |
+
context_dim: 1024
|
44 |
+
use_checkpoint: False
|
45 |
+
legacy: False
|
46 |
+
|
47 |
+
first_stage_config:
|
48 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
49 |
+
params:
|
50 |
+
embed_dim: 4
|
51 |
+
monitor: val/rec_loss
|
52 |
+
ddconfig:
|
53 |
+
double_z: true
|
54 |
+
z_channels: 4
|
55 |
+
resolution: 256
|
56 |
+
in_channels: 3
|
57 |
+
out_ch: 3
|
58 |
+
ch: 128
|
59 |
+
ch_mult:
|
60 |
+
- 1
|
61 |
+
- 2
|
62 |
+
- 4
|
63 |
+
- 4
|
64 |
+
num_res_blocks: 2
|
65 |
+
attn_resolutions: []
|
66 |
+
dropout: 0.0
|
67 |
+
lossconfig:
|
68 |
+
target: torch.nn.Identity
|
69 |
+
|
70 |
+
cond_stage_config:
|
71 |
+
target: modules.xlmr_m18.BertSeriesModelWithTransformation
|
72 |
+
params:
|
73 |
+
name: "XLMR-Large"
|
configs/instruct-pix2pix.yaml
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
+
# See more details in LICENSE.
|
3 |
+
|
4 |
+
model:
|
5 |
+
base_learning_rate: 1.0e-04
|
6 |
+
target: modules.models.diffusion.ddpm_edit.LatentDiffusion
|
7 |
+
params:
|
8 |
+
linear_start: 0.00085
|
9 |
+
linear_end: 0.0120
|
10 |
+
num_timesteps_cond: 1
|
11 |
+
log_every_t: 200
|
12 |
+
timesteps: 1000
|
13 |
+
first_stage_key: edited
|
14 |
+
cond_stage_key: edit
|
15 |
+
# image_size: 64
|
16 |
+
# image_size: 32
|
17 |
+
image_size: 16
|
18 |
+
channels: 4
|
19 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
20 |
+
conditioning_key: hybrid
|
21 |
+
monitor: val/loss_simple_ema
|
22 |
+
scale_factor: 0.18215
|
23 |
+
use_ema: false
|
24 |
+
|
25 |
+
scheduler_config: # 10000 warmup steps
|
26 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
27 |
+
params:
|
28 |
+
warm_up_steps: [ 0 ]
|
29 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
30 |
+
f_start: [ 1.e-6 ]
|
31 |
+
f_max: [ 1. ]
|
32 |
+
f_min: [ 1. ]
|
33 |
+
|
34 |
+
unet_config:
|
35 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
36 |
+
params:
|
37 |
+
image_size: 32 # unused
|
38 |
+
in_channels: 8
|
39 |
+
out_channels: 4
|
40 |
+
model_channels: 320
|
41 |
+
attention_resolutions: [ 4, 2, 1 ]
|
42 |
+
num_res_blocks: 2
|
43 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
44 |
+
num_heads: 8
|
45 |
+
use_spatial_transformer: True
|
46 |
+
transformer_depth: 1
|
47 |
+
context_dim: 768
|
48 |
+
use_checkpoint: False
|
49 |
+
legacy: False
|
50 |
+
|
51 |
+
first_stage_config:
|
52 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
53 |
+
params:
|
54 |
+
embed_dim: 4
|
55 |
+
monitor: val/rec_loss
|
56 |
+
ddconfig:
|
57 |
+
double_z: true
|
58 |
+
z_channels: 4
|
59 |
+
resolution: 256
|
60 |
+
in_channels: 3
|
61 |
+
out_ch: 3
|
62 |
+
ch: 128
|
63 |
+
ch_mult:
|
64 |
+
- 1
|
65 |
+
- 2
|
66 |
+
- 4
|
67 |
+
- 4
|
68 |
+
num_res_blocks: 2
|
69 |
+
attn_resolutions: []
|
70 |
+
dropout: 0.0
|
71 |
+
lossconfig:
|
72 |
+
target: torch.nn.Identity
|
73 |
+
|
74 |
+
cond_stage_config:
|
75 |
+
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
76 |
+
|
77 |
+
data:
|
78 |
+
target: main.DataModuleFromConfig
|
79 |
+
params:
|
80 |
+
batch_size: 128
|
81 |
+
num_workers: 1
|
82 |
+
wrap: false
|
83 |
+
validation:
|
84 |
+
target: edit_dataset.EditDataset
|
85 |
+
params:
|
86 |
+
path: data/clip-filtered-dataset
|
87 |
+
cache_dir: data/
|
88 |
+
cache_name: data_10k
|
89 |
+
split: val
|
90 |
+
min_text_sim: 0.2
|
91 |
+
min_image_sim: 0.75
|
92 |
+
min_direction_sim: 0.2
|
93 |
+
max_samples_per_prompt: 1
|
94 |
+
min_resize_res: 512
|
95 |
+
max_resize_res: 512
|
96 |
+
crop_res: 512
|
97 |
+
output_as_edit: False
|
98 |
+
real_input: True
|
configs/sd3-inference.yaml
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: modules.models.sd3.sd3_model.SD3Inferencer
|
3 |
+
params:
|
4 |
+
shift: 3
|
5 |
+
state_dict: null
|
configs/sd_xl_inpaint.yaml
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: sgm.models.diffusion.DiffusionEngine
|
3 |
+
params:
|
4 |
+
scale_factor: 0.13025
|
5 |
+
disable_first_stage_autocast: True
|
6 |
+
|
7 |
+
denoiser_config:
|
8 |
+
target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser
|
9 |
+
params:
|
10 |
+
num_idx: 1000
|
11 |
+
|
12 |
+
weighting_config:
|
13 |
+
target: sgm.modules.diffusionmodules.denoiser_weighting.EpsWeighting
|
14 |
+
scaling_config:
|
15 |
+
target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling
|
16 |
+
discretization_config:
|
17 |
+
target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization
|
18 |
+
|
19 |
+
network_config:
|
20 |
+
target: sgm.modules.diffusionmodules.openaimodel.UNetModel
|
21 |
+
params:
|
22 |
+
adm_in_channels: 2816
|
23 |
+
num_classes: sequential
|
24 |
+
use_checkpoint: False
|
25 |
+
in_channels: 9
|
26 |
+
out_channels: 4
|
27 |
+
model_channels: 320
|
28 |
+
attention_resolutions: [4, 2]
|
29 |
+
num_res_blocks: 2
|
30 |
+
channel_mult: [1, 2, 4]
|
31 |
+
num_head_channels: 64
|
32 |
+
use_spatial_transformer: True
|
33 |
+
use_linear_in_transformer: True
|
34 |
+
transformer_depth: [1, 2, 10] # note: the first is unused (due to attn_res starting at 2) 32, 16, 8 --> 64, 32, 16
|
35 |
+
context_dim: 2048
|
36 |
+
spatial_transformer_attn_type: softmax-xformers
|
37 |
+
legacy: False
|
38 |
+
|
39 |
+
conditioner_config:
|
40 |
+
target: sgm.modules.GeneralConditioner
|
41 |
+
params:
|
42 |
+
emb_models:
|
43 |
+
# crossattn cond
|
44 |
+
- is_trainable: False
|
45 |
+
input_key: txt
|
46 |
+
target: sgm.modules.encoders.modules.FrozenCLIPEmbedder
|
47 |
+
params:
|
48 |
+
layer: hidden
|
49 |
+
layer_idx: 11
|
50 |
+
# crossattn and vector cond
|
51 |
+
- is_trainable: False
|
52 |
+
input_key: txt
|
53 |
+
target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2
|
54 |
+
params:
|
55 |
+
arch: ViT-bigG-14
|
56 |
+
version: laion2b_s39b_b160k
|
57 |
+
freeze: True
|
58 |
+
layer: penultimate
|
59 |
+
always_return_pooled: True
|
60 |
+
legacy: False
|
61 |
+
# vector cond
|
62 |
+
- is_trainable: False
|
63 |
+
input_key: original_size_as_tuple
|
64 |
+
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
65 |
+
params:
|
66 |
+
outdim: 256 # multiplied by two
|
67 |
+
# vector cond
|
68 |
+
- is_trainable: False
|
69 |
+
input_key: crop_coords_top_left
|
70 |
+
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
71 |
+
params:
|
72 |
+
outdim: 256 # multiplied by two
|
73 |
+
# vector cond
|
74 |
+
- is_trainable: False
|
75 |
+
input_key: target_size_as_tuple
|
76 |
+
target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
|
77 |
+
params:
|
78 |
+
outdim: 256 # multiplied by two
|
79 |
+
|
80 |
+
first_stage_config:
|
81 |
+
target: sgm.models.autoencoder.AutoencoderKLInferenceWrapper
|
82 |
+
params:
|
83 |
+
embed_dim: 4
|
84 |
+
monitor: val/rec_loss
|
85 |
+
ddconfig:
|
86 |
+
attn_type: vanilla-xformers
|
87 |
+
double_z: true
|
88 |
+
z_channels: 4
|
89 |
+
resolution: 256
|
90 |
+
in_channels: 3
|
91 |
+
out_ch: 3
|
92 |
+
ch: 128
|
93 |
+
ch_mult: [1, 2, 4, 4]
|
94 |
+
num_res_blocks: 2
|
95 |
+
attn_resolutions: []
|
96 |
+
dropout: 0.0
|
97 |
+
lossconfig:
|
98 |
+
target: torch.nn.Identity
|
configs/v1-inference.yaml
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
base_learning_rate: 1.0e-04
|
3 |
+
target: ldm.models.diffusion.ddpm.LatentDiffusion
|
4 |
+
params:
|
5 |
+
linear_start: 0.00085
|
6 |
+
linear_end: 0.0120
|
7 |
+
num_timesteps_cond: 1
|
8 |
+
log_every_t: 200
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: "jpg"
|
11 |
+
cond_stage_key: "txt"
|
12 |
+
image_size: 64
|
13 |
+
channels: 4
|
14 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
15 |
+
conditioning_key: crossattn
|
16 |
+
monitor: val/loss_simple_ema
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: False
|
19 |
+
|
20 |
+
scheduler_config: # 10000 warmup steps
|
21 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
22 |
+
params:
|
23 |
+
warm_up_steps: [ 10000 ]
|
24 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
25 |
+
f_start: [ 1.e-6 ]
|
26 |
+
f_max: [ 1. ]
|
27 |
+
f_min: [ 1. ]
|
28 |
+
|
29 |
+
unet_config:
|
30 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
31 |
+
params:
|
32 |
+
image_size: 32 # unused
|
33 |
+
in_channels: 4
|
34 |
+
out_channels: 4
|
35 |
+
model_channels: 320
|
36 |
+
attention_resolutions: [ 4, 2, 1 ]
|
37 |
+
num_res_blocks: 2
|
38 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
39 |
+
num_heads: 8
|
40 |
+
use_spatial_transformer: True
|
41 |
+
transformer_depth: 1
|
42 |
+
context_dim: 768
|
43 |
+
use_checkpoint: False
|
44 |
+
legacy: False
|
45 |
+
|
46 |
+
first_stage_config:
|
47 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
48 |
+
params:
|
49 |
+
embed_dim: 4
|
50 |
+
monitor: val/rec_loss
|
51 |
+
ddconfig:
|
52 |
+
double_z: true
|
53 |
+
z_channels: 4
|
54 |
+
resolution: 256
|
55 |
+
in_channels: 3
|
56 |
+
out_ch: 3
|
57 |
+
ch: 128
|
58 |
+
ch_mult:
|
59 |
+
- 1
|
60 |
+
- 2
|
61 |
+
- 4
|
62 |
+
- 4
|
63 |
+
num_res_blocks: 2
|
64 |
+
attn_resolutions: []
|
65 |
+
dropout: 0.0
|
66 |
+
lossconfig:
|
67 |
+
target: torch.nn.Identity
|
68 |
+
|
69 |
+
cond_stage_config:
|
70 |
+
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
configs/v1-inpainting-inference.yaml
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
base_learning_rate: 7.5e-05
|
3 |
+
target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion
|
4 |
+
params:
|
5 |
+
linear_start: 0.00085
|
6 |
+
linear_end: 0.0120
|
7 |
+
num_timesteps_cond: 1
|
8 |
+
log_every_t: 200
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: "jpg"
|
11 |
+
cond_stage_key: "txt"
|
12 |
+
image_size: 64
|
13 |
+
channels: 4
|
14 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
15 |
+
conditioning_key: hybrid # important
|
16 |
+
monitor: val/loss_simple_ema
|
17 |
+
scale_factor: 0.18215
|
18 |
+
finetune_keys: null
|
19 |
+
|
20 |
+
scheduler_config: # 10000 warmup steps
|
21 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
22 |
+
params:
|
23 |
+
warm_up_steps: [ 2500 ] # NOTE for resuming. use 10000 if starting from scratch
|
24 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
25 |
+
f_start: [ 1.e-6 ]
|
26 |
+
f_max: [ 1. ]
|
27 |
+
f_min: [ 1. ]
|
28 |
+
|
29 |
+
unet_config:
|
30 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
31 |
+
params:
|
32 |
+
image_size: 32 # unused
|
33 |
+
in_channels: 9 # 4 data + 4 downscaled image + 1 mask
|
34 |
+
out_channels: 4
|
35 |
+
model_channels: 320
|
36 |
+
attention_resolutions: [ 4, 2, 1 ]
|
37 |
+
num_res_blocks: 2
|
38 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
39 |
+
num_heads: 8
|
40 |
+
use_spatial_transformer: True
|
41 |
+
transformer_depth: 1
|
42 |
+
context_dim: 768
|
43 |
+
use_checkpoint: False
|
44 |
+
legacy: False
|
45 |
+
|
46 |
+
first_stage_config:
|
47 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
48 |
+
params:
|
49 |
+
embed_dim: 4
|
50 |
+
monitor: val/rec_loss
|
51 |
+
ddconfig:
|
52 |
+
double_z: true
|
53 |
+
z_channels: 4
|
54 |
+
resolution: 256
|
55 |
+
in_channels: 3
|
56 |
+
out_ch: 3
|
57 |
+
ch: 128
|
58 |
+
ch_mult:
|
59 |
+
- 1
|
60 |
+
- 2
|
61 |
+
- 4
|
62 |
+
- 4
|
63 |
+
num_res_blocks: 2
|
64 |
+
attn_resolutions: []
|
65 |
+
dropout: 0.0
|
66 |
+
lossconfig:
|
67 |
+
target: torch.nn.Identity
|
68 |
+
|
69 |
+
cond_stage_config:
|
70 |
+
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
environment-wsl2.yaml
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: automatic
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- defaults
|
5 |
+
dependencies:
|
6 |
+
- python=3.10
|
7 |
+
- pip=23.0
|
8 |
+
- cudatoolkit=11.8
|
9 |
+
- pytorch=2.0
|
10 |
+
- torchvision=0.15
|
11 |
+
- numpy=1.23
|
extensions-builtin/LDSR/ldsr_model_arch.py
ADDED
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gc
|
3 |
+
import time
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
import torchvision
|
8 |
+
from PIL import Image
|
9 |
+
from einops import rearrange, repeat
|
10 |
+
from omegaconf import OmegaConf
|
11 |
+
import safetensors.torch
|
12 |
+
|
13 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
14 |
+
from ldm.util import instantiate_from_config, ismap
|
15 |
+
from modules import shared, sd_hijack, devices
|
16 |
+
|
17 |
+
cached_ldsr_model: torch.nn.Module = None
|
18 |
+
|
19 |
+
|
20 |
+
# Create LDSR Class
|
21 |
+
class LDSR:
|
22 |
+
def load_model_from_config(self, half_attention):
|
23 |
+
global cached_ldsr_model
|
24 |
+
|
25 |
+
if shared.opts.ldsr_cached and cached_ldsr_model is not None:
|
26 |
+
print("Loading model from cache")
|
27 |
+
model: torch.nn.Module = cached_ldsr_model
|
28 |
+
else:
|
29 |
+
print(f"Loading model from {self.modelPath}")
|
30 |
+
_, extension = os.path.splitext(self.modelPath)
|
31 |
+
if extension.lower() == ".safetensors":
|
32 |
+
pl_sd = safetensors.torch.load_file(self.modelPath, device="cpu")
|
33 |
+
else:
|
34 |
+
pl_sd = torch.load(self.modelPath, map_location="cpu")
|
35 |
+
sd = pl_sd["state_dict"] if "state_dict" in pl_sd else pl_sd
|
36 |
+
config = OmegaConf.load(self.yamlPath)
|
37 |
+
config.model.target = "ldm.models.diffusion.ddpm.LatentDiffusionV1"
|
38 |
+
model: torch.nn.Module = instantiate_from_config(config.model)
|
39 |
+
model.load_state_dict(sd, strict=False)
|
40 |
+
model = model.to(shared.device)
|
41 |
+
if half_attention:
|
42 |
+
model = model.half()
|
43 |
+
if shared.cmd_opts.opt_channelslast:
|
44 |
+
model = model.to(memory_format=torch.channels_last)
|
45 |
+
|
46 |
+
sd_hijack.model_hijack.hijack(model) # apply optimization
|
47 |
+
model.eval()
|
48 |
+
|
49 |
+
if shared.opts.ldsr_cached:
|
50 |
+
cached_ldsr_model = model
|
51 |
+
|
52 |
+
return {"model": model}
|
53 |
+
|
54 |
+
def __init__(self, model_path, yaml_path):
|
55 |
+
self.modelPath = model_path
|
56 |
+
self.yamlPath = yaml_path
|
57 |
+
|
58 |
+
@staticmethod
|
59 |
+
def run(model, selected_path, custom_steps, eta):
|
60 |
+
example = get_cond(selected_path)
|
61 |
+
|
62 |
+
n_runs = 1
|
63 |
+
guider = None
|
64 |
+
ckwargs = None
|
65 |
+
ddim_use_x0_pred = False
|
66 |
+
temperature = 1.
|
67 |
+
eta = eta
|
68 |
+
custom_shape = None
|
69 |
+
|
70 |
+
height, width = example["image"].shape[1:3]
|
71 |
+
split_input = height >= 128 and width >= 128
|
72 |
+
|
73 |
+
if split_input:
|
74 |
+
ks = 128
|
75 |
+
stride = 64
|
76 |
+
vqf = 4 #
|
77 |
+
model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
|
78 |
+
"vqf": vqf,
|
79 |
+
"patch_distributed_vq": True,
|
80 |
+
"tie_braker": False,
|
81 |
+
"clip_max_weight": 0.5,
|
82 |
+
"clip_min_weight": 0.01,
|
83 |
+
"clip_max_tie_weight": 0.5,
|
84 |
+
"clip_min_tie_weight": 0.01}
|
85 |
+
else:
|
86 |
+
if hasattr(model, "split_input_params"):
|
87 |
+
delattr(model, "split_input_params")
|
88 |
+
|
89 |
+
x_t = None
|
90 |
+
logs = None
|
91 |
+
for _ in range(n_runs):
|
92 |
+
if custom_shape is not None:
|
93 |
+
x_t = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
|
94 |
+
x_t = repeat(x_t, '1 c h w -> b c h w', b=custom_shape[0])
|
95 |
+
|
96 |
+
logs = make_convolutional_sample(example, model,
|
97 |
+
custom_steps=custom_steps,
|
98 |
+
eta=eta, quantize_x0=False,
|
99 |
+
custom_shape=custom_shape,
|
100 |
+
temperature=temperature, noise_dropout=0.,
|
101 |
+
corrector=guider, corrector_kwargs=ckwargs, x_T=x_t,
|
102 |
+
ddim_use_x0_pred=ddim_use_x0_pred
|
103 |
+
)
|
104 |
+
return logs
|
105 |
+
|
106 |
+
def super_resolution(self, image, steps=100, target_scale=2, half_attention=False):
|
107 |
+
model = self.load_model_from_config(half_attention)
|
108 |
+
|
109 |
+
# Run settings
|
110 |
+
diffusion_steps = int(steps)
|
111 |
+
eta = 1.0
|
112 |
+
|
113 |
+
|
114 |
+
gc.collect()
|
115 |
+
devices.torch_gc()
|
116 |
+
|
117 |
+
im_og = image
|
118 |
+
width_og, height_og = im_og.size
|
119 |
+
# If we can adjust the max upscale size, then the 4 below should be our variable
|
120 |
+
down_sample_rate = target_scale / 4
|
121 |
+
wd = width_og * down_sample_rate
|
122 |
+
hd = height_og * down_sample_rate
|
123 |
+
width_downsampled_pre = int(np.ceil(wd))
|
124 |
+
height_downsampled_pre = int(np.ceil(hd))
|
125 |
+
|
126 |
+
if down_sample_rate != 1:
|
127 |
+
print(
|
128 |
+
f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')
|
129 |
+
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
|
130 |
+
else:
|
131 |
+
print(f"Down sample rate is 1 from {target_scale} / 4 (Not downsampling)")
|
132 |
+
|
133 |
+
# pad width and height to multiples of 64, pads with the edge values of image to avoid artifacts
|
134 |
+
pad_w, pad_h = np.max(((2, 2), np.ceil(np.array(im_og.size) / 64).astype(int)), axis=0) * 64 - im_og.size
|
135 |
+
im_padded = Image.fromarray(np.pad(np.array(im_og), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge'))
|
136 |
+
|
137 |
+
logs = self.run(model["model"], im_padded, diffusion_steps, eta)
|
138 |
+
|
139 |
+
sample = logs["sample"]
|
140 |
+
sample = sample.detach().cpu()
|
141 |
+
sample = torch.clamp(sample, -1., 1.)
|
142 |
+
sample = (sample + 1.) / 2. * 255
|
143 |
+
sample = sample.numpy().astype(np.uint8)
|
144 |
+
sample = np.transpose(sample, (0, 2, 3, 1))
|
145 |
+
a = Image.fromarray(sample[0])
|
146 |
+
|
147 |
+
# remove padding
|
148 |
+
a = a.crop((0, 0) + tuple(np.array(im_og.size) * 4))
|
149 |
+
|
150 |
+
del model
|
151 |
+
gc.collect()
|
152 |
+
devices.torch_gc()
|
153 |
+
|
154 |
+
return a
|
155 |
+
|
156 |
+
|
157 |
+
def get_cond(selected_path):
|
158 |
+
example = {}
|
159 |
+
up_f = 4
|
160 |
+
c = selected_path.convert('RGB')
|
161 |
+
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
|
162 |
+
c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]],
|
163 |
+
antialias=True)
|
164 |
+
c_up = rearrange(c_up, '1 c h w -> 1 h w c')
|
165 |
+
c = rearrange(c, '1 c h w -> 1 h w c')
|
166 |
+
c = 2. * c - 1.
|
167 |
+
|
168 |
+
c = c.to(shared.device)
|
169 |
+
example["LR_image"] = c
|
170 |
+
example["image"] = c_up
|
171 |
+
|
172 |
+
return example
|
173 |
+
|
174 |
+
|
175 |
+
@torch.no_grad()
|
176 |
+
def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
|
177 |
+
mask=None, x0=None, quantize_x0=False, temperature=1., score_corrector=None,
|
178 |
+
corrector_kwargs=None, x_t=None
|
179 |
+
):
|
180 |
+
ddim = DDIMSampler(model)
|
181 |
+
bs = shape[0]
|
182 |
+
shape = shape[1:]
|
183 |
+
print(f"Sampling with eta = {eta}; steps: {steps}")
|
184 |
+
samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
|
185 |
+
normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
|
186 |
+
mask=mask, x0=x0, temperature=temperature, verbose=False,
|
187 |
+
score_corrector=score_corrector,
|
188 |
+
corrector_kwargs=corrector_kwargs, x_t=x_t)
|
189 |
+
|
190 |
+
return samples, intermediates
|
191 |
+
|
192 |
+
|
193 |
+
@torch.no_grad()
|
194 |
+
def make_convolutional_sample(batch, model, custom_steps=None, eta=1.0, quantize_x0=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
|
195 |
+
corrector_kwargs=None, x_T=None, ddim_use_x0_pred=False):
|
196 |
+
log = {}
|
197 |
+
|
198 |
+
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
|
199 |
+
return_first_stage_outputs=True,
|
200 |
+
force_c_encode=not (hasattr(model, 'split_input_params')
|
201 |
+
and model.cond_stage_key == 'coordinates_bbox'),
|
202 |
+
return_original_cond=True)
|
203 |
+
|
204 |
+
if custom_shape is not None:
|
205 |
+
z = torch.randn(custom_shape)
|
206 |
+
print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
|
207 |
+
|
208 |
+
z0 = None
|
209 |
+
|
210 |
+
log["input"] = x
|
211 |
+
log["reconstruction"] = xrec
|
212 |
+
|
213 |
+
if ismap(xc):
|
214 |
+
log["original_conditioning"] = model.to_rgb(xc)
|
215 |
+
if hasattr(model, 'cond_stage_key'):
|
216 |
+
log[model.cond_stage_key] = model.to_rgb(xc)
|
217 |
+
|
218 |
+
else:
|
219 |
+
log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
|
220 |
+
if model.cond_stage_model:
|
221 |
+
log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
|
222 |
+
if model.cond_stage_key == 'class_label':
|
223 |
+
log[model.cond_stage_key] = xc[model.cond_stage_key]
|
224 |
+
|
225 |
+
with model.ema_scope("Plotting"):
|
226 |
+
t0 = time.time()
|
227 |
+
|
228 |
+
sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
|
229 |
+
eta=eta,
|
230 |
+
quantize_x0=quantize_x0, mask=None, x0=z0,
|
231 |
+
temperature=temperature, score_corrector=corrector, corrector_kwargs=corrector_kwargs,
|
232 |
+
x_t=x_T)
|
233 |
+
t1 = time.time()
|
234 |
+
|
235 |
+
if ddim_use_x0_pred:
|
236 |
+
sample = intermediates['pred_x0'][-1]
|
237 |
+
|
238 |
+
x_sample = model.decode_first_stage(sample)
|
239 |
+
|
240 |
+
try:
|
241 |
+
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
|
242 |
+
log["sample_noquant"] = x_sample_noquant
|
243 |
+
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
|
244 |
+
except Exception:
|
245 |
+
pass
|
246 |
+
|
247 |
+
log["sample"] = x_sample
|
248 |
+
log["time"] = t1 - t0
|
249 |
+
|
250 |
+
return log
|
extensions-builtin/LDSR/preload.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from modules import paths
|
3 |
+
|
4 |
+
|
5 |
+
def preload(parser):
|
6 |
+
parser.add_argument("--ldsr-models-path", type=str, help="Path to directory with LDSR model file(s).", default=os.path.join(paths.models_path, 'LDSR'))
|
extensions-builtin/LDSR/scripts/ldsr_model.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
from modules.modelloader import load_file_from_url
|
4 |
+
from modules.upscaler import Upscaler, UpscalerData
|
5 |
+
from ldsr_model_arch import LDSR
|
6 |
+
from modules import shared, script_callbacks, errors
|
7 |
+
import sd_hijack_autoencoder # noqa: F401
|
8 |
+
import sd_hijack_ddpm_v1 # noqa: F401
|
9 |
+
|
10 |
+
|
11 |
+
class UpscalerLDSR(Upscaler):
|
12 |
+
def __init__(self, user_path):
|
13 |
+
self.name = "LDSR"
|
14 |
+
self.user_path = user_path
|
15 |
+
self.model_url = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1"
|
16 |
+
self.yaml_url = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1"
|
17 |
+
super().__init__()
|
18 |
+
scaler_data = UpscalerData("LDSR", None, self)
|
19 |
+
self.scalers = [scaler_data]
|
20 |
+
|
21 |
+
def load_model(self, path: str):
|
22 |
+
# Remove incorrect project.yaml file if too big
|
23 |
+
yaml_path = os.path.join(self.model_path, "project.yaml")
|
24 |
+
old_model_path = os.path.join(self.model_path, "model.pth")
|
25 |
+
new_model_path = os.path.join(self.model_path, "model.ckpt")
|
26 |
+
|
27 |
+
local_model_paths = self.find_models(ext_filter=[".ckpt", ".safetensors"])
|
28 |
+
local_ckpt_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("model.ckpt")]), None)
|
29 |
+
local_safetensors_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("model.safetensors")]), None)
|
30 |
+
local_yaml_path = next(iter([local_model for local_model in local_model_paths if local_model.endswith("project.yaml")]), None)
|
31 |
+
|
32 |
+
if os.path.exists(yaml_path):
|
33 |
+
statinfo = os.stat(yaml_path)
|
34 |
+
if statinfo.st_size >= 10485760:
|
35 |
+
print("Removing invalid LDSR YAML file.")
|
36 |
+
os.remove(yaml_path)
|
37 |
+
|
38 |
+
if os.path.exists(old_model_path):
|
39 |
+
print("Renaming model from model.pth to model.ckpt")
|
40 |
+
os.rename(old_model_path, new_model_path)
|
41 |
+
|
42 |
+
if local_safetensors_path is not None and os.path.exists(local_safetensors_path):
|
43 |
+
model = local_safetensors_path
|
44 |
+
else:
|
45 |
+
model = local_ckpt_path or load_file_from_url(self.model_url, model_dir=self.model_download_path, file_name="model.ckpt")
|
46 |
+
|
47 |
+
yaml = local_yaml_path or load_file_from_url(self.yaml_url, model_dir=self.model_download_path, file_name="project.yaml")
|
48 |
+
|
49 |
+
return LDSR(model, yaml)
|
50 |
+
|
51 |
+
def do_upscale(self, img, path):
|
52 |
+
try:
|
53 |
+
ldsr = self.load_model(path)
|
54 |
+
except Exception:
|
55 |
+
errors.report(f"Failed loading LDSR model {path}", exc_info=True)
|
56 |
+
return img
|
57 |
+
ddim_steps = shared.opts.ldsr_steps
|
58 |
+
return ldsr.super_resolution(img, ddim_steps, self.scale)
|
59 |
+
|
60 |
+
|
61 |
+
def on_ui_settings():
|
62 |
+
import gradio as gr
|
63 |
+
|
64 |
+
shared.opts.add_option("ldsr_steps", shared.OptionInfo(100, "LDSR processing steps. Lower = faster", gr.Slider, {"minimum": 1, "maximum": 200, "step": 1}, section=('upscaling', "Upscaling")))
|
65 |
+
shared.opts.add_option("ldsr_cached", shared.OptionInfo(False, "Cache LDSR model in memory", gr.Checkbox, {"interactive": True}, section=('upscaling', "Upscaling")))
|
66 |
+
|
67 |
+
|
68 |
+
script_callbacks.on_ui_settings(on_ui_settings)
|
extensions-builtin/LDSR/sd_hijack_autoencoder.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# The content of this file comes from the ldm/models/autoencoder.py file of the compvis/stable-diffusion repo
|
2 |
+
# The VQModel & VQModelInterface were subsequently removed from ldm/models/autoencoder.py when we moved to the stability-ai/stablediffusion repo
|
3 |
+
# As the LDSR upscaler relies on VQModel & VQModelInterface, the hijack aims to put them back into the ldm.models.autoencoder
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import pytorch_lightning as pl
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from contextlib import contextmanager
|
9 |
+
|
10 |
+
from torch.optim.lr_scheduler import LambdaLR
|
11 |
+
|
12 |
+
from ldm.modules.ema import LitEma
|
13 |
+
from vqvae_quantize import VectorQuantizer2 as VectorQuantizer
|
14 |
+
from ldm.modules.diffusionmodules.model import Encoder, Decoder
|
15 |
+
from ldm.util import instantiate_from_config
|
16 |
+
|
17 |
+
import ldm.models.autoencoder
|
18 |
+
from packaging import version
|
19 |
+
|
20 |
+
class VQModel(pl.LightningModule):
|
21 |
+
def __init__(self,
|
22 |
+
ddconfig,
|
23 |
+
lossconfig,
|
24 |
+
n_embed,
|
25 |
+
embed_dim,
|
26 |
+
ckpt_path=None,
|
27 |
+
ignore_keys=None,
|
28 |
+
image_key="image",
|
29 |
+
colorize_nlabels=None,
|
30 |
+
monitor=None,
|
31 |
+
batch_resize_range=None,
|
32 |
+
scheduler_config=None,
|
33 |
+
lr_g_factor=1.0,
|
34 |
+
remap=None,
|
35 |
+
sane_index_shape=False, # tell vector quantizer to return indices as bhw
|
36 |
+
use_ema=False
|
37 |
+
):
|
38 |
+
super().__init__()
|
39 |
+
self.embed_dim = embed_dim
|
40 |
+
self.n_embed = n_embed
|
41 |
+
self.image_key = image_key
|
42 |
+
self.encoder = Encoder(**ddconfig)
|
43 |
+
self.decoder = Decoder(**ddconfig)
|
44 |
+
self.loss = instantiate_from_config(lossconfig)
|
45 |
+
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
|
46 |
+
remap=remap,
|
47 |
+
sane_index_shape=sane_index_shape)
|
48 |
+
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
|
49 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
50 |
+
if colorize_nlabels is not None:
|
51 |
+
assert type(colorize_nlabels)==int
|
52 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
53 |
+
if monitor is not None:
|
54 |
+
self.monitor = monitor
|
55 |
+
self.batch_resize_range = batch_resize_range
|
56 |
+
if self.batch_resize_range is not None:
|
57 |
+
print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
|
58 |
+
|
59 |
+
self.use_ema = use_ema
|
60 |
+
if self.use_ema:
|
61 |
+
self.model_ema = LitEma(self)
|
62 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
63 |
+
|
64 |
+
if ckpt_path is not None:
|
65 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [])
|
66 |
+
self.scheduler_config = scheduler_config
|
67 |
+
self.lr_g_factor = lr_g_factor
|
68 |
+
|
69 |
+
@contextmanager
|
70 |
+
def ema_scope(self, context=None):
|
71 |
+
if self.use_ema:
|
72 |
+
self.model_ema.store(self.parameters())
|
73 |
+
self.model_ema.copy_to(self)
|
74 |
+
if context is not None:
|
75 |
+
print(f"{context}: Switched to EMA weights")
|
76 |
+
try:
|
77 |
+
yield None
|
78 |
+
finally:
|
79 |
+
if self.use_ema:
|
80 |
+
self.model_ema.restore(self.parameters())
|
81 |
+
if context is not None:
|
82 |
+
print(f"{context}: Restored training weights")
|
83 |
+
|
84 |
+
def init_from_ckpt(self, path, ignore_keys=None):
|
85 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
86 |
+
keys = list(sd.keys())
|
87 |
+
for k in keys:
|
88 |
+
for ik in ignore_keys or []:
|
89 |
+
if k.startswith(ik):
|
90 |
+
print("Deleting key {} from state_dict.".format(k))
|
91 |
+
del sd[k]
|
92 |
+
missing, unexpected = self.load_state_dict(sd, strict=False)
|
93 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
94 |
+
if missing:
|
95 |
+
print(f"Missing Keys: {missing}")
|
96 |
+
if unexpected:
|
97 |
+
print(f"Unexpected Keys: {unexpected}")
|
98 |
+
|
99 |
+
def on_train_batch_end(self, *args, **kwargs):
|
100 |
+
if self.use_ema:
|
101 |
+
self.model_ema(self)
|
102 |
+
|
103 |
+
def encode(self, x):
|
104 |
+
h = self.encoder(x)
|
105 |
+
h = self.quant_conv(h)
|
106 |
+
quant, emb_loss, info = self.quantize(h)
|
107 |
+
return quant, emb_loss, info
|
108 |
+
|
109 |
+
def encode_to_prequant(self, x):
|
110 |
+
h = self.encoder(x)
|
111 |
+
h = self.quant_conv(h)
|
112 |
+
return h
|
113 |
+
|
114 |
+
def decode(self, quant):
|
115 |
+
quant = self.post_quant_conv(quant)
|
116 |
+
dec = self.decoder(quant)
|
117 |
+
return dec
|
118 |
+
|
119 |
+
def decode_code(self, code_b):
|
120 |
+
quant_b = self.quantize.embed_code(code_b)
|
121 |
+
dec = self.decode(quant_b)
|
122 |
+
return dec
|
123 |
+
|
124 |
+
def forward(self, input, return_pred_indices=False):
|
125 |
+
quant, diff, (_,_,ind) = self.encode(input)
|
126 |
+
dec = self.decode(quant)
|
127 |
+
if return_pred_indices:
|
128 |
+
return dec, diff, ind
|
129 |
+
return dec, diff
|
130 |
+
|
131 |
+
def get_input(self, batch, k):
|
132 |
+
x = batch[k]
|
133 |
+
if len(x.shape) == 3:
|
134 |
+
x = x[..., None]
|
135 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
136 |
+
if self.batch_resize_range is not None:
|
137 |
+
lower_size = self.batch_resize_range[0]
|
138 |
+
upper_size = self.batch_resize_range[1]
|
139 |
+
if self.global_step <= 4:
|
140 |
+
# do the first few batches with max size to avoid later oom
|
141 |
+
new_resize = upper_size
|
142 |
+
else:
|
143 |
+
new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
|
144 |
+
if new_resize != x.shape[2]:
|
145 |
+
x = F.interpolate(x, size=new_resize, mode="bicubic")
|
146 |
+
x = x.detach()
|
147 |
+
return x
|
148 |
+
|
149 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
150 |
+
# https://github.com/pytorch/pytorch/issues/37142
|
151 |
+
# try not to fool the heuristics
|
152 |
+
x = self.get_input(batch, self.image_key)
|
153 |
+
xrec, qloss, ind = self(x, return_pred_indices=True)
|
154 |
+
|
155 |
+
if optimizer_idx == 0:
|
156 |
+
# autoencode
|
157 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
158 |
+
last_layer=self.get_last_layer(), split="train",
|
159 |
+
predicted_indices=ind)
|
160 |
+
|
161 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
162 |
+
return aeloss
|
163 |
+
|
164 |
+
if optimizer_idx == 1:
|
165 |
+
# discriminator
|
166 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
167 |
+
last_layer=self.get_last_layer(), split="train")
|
168 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
169 |
+
return discloss
|
170 |
+
|
171 |
+
def validation_step(self, batch, batch_idx):
|
172 |
+
log_dict = self._validation_step(batch, batch_idx)
|
173 |
+
with self.ema_scope():
|
174 |
+
self._validation_step(batch, batch_idx, suffix="_ema")
|
175 |
+
return log_dict
|
176 |
+
|
177 |
+
def _validation_step(self, batch, batch_idx, suffix=""):
|
178 |
+
x = self.get_input(batch, self.image_key)
|
179 |
+
xrec, qloss, ind = self(x, return_pred_indices=True)
|
180 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
|
181 |
+
self.global_step,
|
182 |
+
last_layer=self.get_last_layer(),
|
183 |
+
split="val"+suffix,
|
184 |
+
predicted_indices=ind
|
185 |
+
)
|
186 |
+
|
187 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
|
188 |
+
self.global_step,
|
189 |
+
last_layer=self.get_last_layer(),
|
190 |
+
split="val"+suffix,
|
191 |
+
predicted_indices=ind
|
192 |
+
)
|
193 |
+
rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
|
194 |
+
self.log(f"val{suffix}/rec_loss", rec_loss,
|
195 |
+
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
196 |
+
self.log(f"val{suffix}/aeloss", aeloss,
|
197 |
+
prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
198 |
+
if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
199 |
+
del log_dict_ae[f"val{suffix}/rec_loss"]
|
200 |
+
self.log_dict(log_dict_ae)
|
201 |
+
self.log_dict(log_dict_disc)
|
202 |
+
return self.log_dict
|
203 |
+
|
204 |
+
def configure_optimizers(self):
|
205 |
+
lr_d = self.learning_rate
|
206 |
+
lr_g = self.lr_g_factor*self.learning_rate
|
207 |
+
print("lr_d", lr_d)
|
208 |
+
print("lr_g", lr_g)
|
209 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
210 |
+
list(self.decoder.parameters())+
|
211 |
+
list(self.quantize.parameters())+
|
212 |
+
list(self.quant_conv.parameters())+
|
213 |
+
list(self.post_quant_conv.parameters()),
|
214 |
+
lr=lr_g, betas=(0.5, 0.9))
|
215 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
216 |
+
lr=lr_d, betas=(0.5, 0.9))
|
217 |
+
|
218 |
+
if self.scheduler_config is not None:
|
219 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
220 |
+
|
221 |
+
print("Setting up LambdaLR scheduler...")
|
222 |
+
scheduler = [
|
223 |
+
{
|
224 |
+
'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
|
225 |
+
'interval': 'step',
|
226 |
+
'frequency': 1
|
227 |
+
},
|
228 |
+
{
|
229 |
+
'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
|
230 |
+
'interval': 'step',
|
231 |
+
'frequency': 1
|
232 |
+
},
|
233 |
+
]
|
234 |
+
return [opt_ae, opt_disc], scheduler
|
235 |
+
return [opt_ae, opt_disc], []
|
236 |
+
|
237 |
+
def get_last_layer(self):
|
238 |
+
return self.decoder.conv_out.weight
|
239 |
+
|
240 |
+
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
241 |
+
log = {}
|
242 |
+
x = self.get_input(batch, self.image_key)
|
243 |
+
x = x.to(self.device)
|
244 |
+
if only_inputs:
|
245 |
+
log["inputs"] = x
|
246 |
+
return log
|
247 |
+
xrec, _ = self(x)
|
248 |
+
if x.shape[1] > 3:
|
249 |
+
# colorize with random projection
|
250 |
+
assert xrec.shape[1] > 3
|
251 |
+
x = self.to_rgb(x)
|
252 |
+
xrec = self.to_rgb(xrec)
|
253 |
+
log["inputs"] = x
|
254 |
+
log["reconstructions"] = xrec
|
255 |
+
if plot_ema:
|
256 |
+
with self.ema_scope():
|
257 |
+
xrec_ema, _ = self(x)
|
258 |
+
if x.shape[1] > 3:
|
259 |
+
xrec_ema = self.to_rgb(xrec_ema)
|
260 |
+
log["reconstructions_ema"] = xrec_ema
|
261 |
+
return log
|
262 |
+
|
263 |
+
def to_rgb(self, x):
|
264 |
+
assert self.image_key == "segmentation"
|
265 |
+
if not hasattr(self, "colorize"):
|
266 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
267 |
+
x = F.conv2d(x, weight=self.colorize)
|
268 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
269 |
+
return x
|
270 |
+
|
271 |
+
|
272 |
+
class VQModelInterface(VQModel):
|
273 |
+
def __init__(self, embed_dim, *args, **kwargs):
|
274 |
+
super().__init__(*args, embed_dim=embed_dim, **kwargs)
|
275 |
+
self.embed_dim = embed_dim
|
276 |
+
|
277 |
+
def encode(self, x):
|
278 |
+
h = self.encoder(x)
|
279 |
+
h = self.quant_conv(h)
|
280 |
+
return h
|
281 |
+
|
282 |
+
def decode(self, h, force_not_quantize=False):
|
283 |
+
# also go through quantization layer
|
284 |
+
if not force_not_quantize:
|
285 |
+
quant, emb_loss, info = self.quantize(h)
|
286 |
+
else:
|
287 |
+
quant = h
|
288 |
+
quant = self.post_quant_conv(quant)
|
289 |
+
dec = self.decoder(quant)
|
290 |
+
return dec
|
291 |
+
|
292 |
+
ldm.models.autoencoder.VQModel = VQModel
|
293 |
+
ldm.models.autoencoder.VQModelInterface = VQModelInterface
|
extensions-builtin/LDSR/sd_hijack_ddpm_v1.py
ADDED
@@ -0,0 +1,1443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
|
2 |
+
# Original filename: ldm/models/diffusion/ddpm.py
|
3 |
+
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
|
4 |
+
# Some models such as LDSR require VQ to work correctly
|
5 |
+
# The classes are suffixed with "V1" and added back to the "ldm.models.diffusion.ddpm" module
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import numpy as np
|
10 |
+
import pytorch_lightning as pl
|
11 |
+
from torch.optim.lr_scheduler import LambdaLR
|
12 |
+
from einops import rearrange, repeat
|
13 |
+
from contextlib import contextmanager
|
14 |
+
from functools import partial
|
15 |
+
from tqdm import tqdm
|
16 |
+
from torchvision.utils import make_grid
|
17 |
+
from pytorch_lightning.utilities.distributed import rank_zero_only
|
18 |
+
|
19 |
+
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
|
20 |
+
from ldm.modules.ema import LitEma
|
21 |
+
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
|
22 |
+
from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
|
23 |
+
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
|
24 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
25 |
+
|
26 |
+
import ldm.models.diffusion.ddpm
|
27 |
+
|
28 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
29 |
+
'crossattn': 'c_crossattn',
|
30 |
+
'adm': 'y'}
|
31 |
+
|
32 |
+
|
33 |
+
def disabled_train(self, mode=True):
|
34 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
35 |
+
does not change anymore."""
|
36 |
+
return self
|
37 |
+
|
38 |
+
|
39 |
+
def uniform_on_device(r1, r2, shape, device):
|
40 |
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
41 |
+
|
42 |
+
|
43 |
+
class DDPMV1(pl.LightningModule):
|
44 |
+
# classic DDPM with Gaussian diffusion, in image space
|
45 |
+
def __init__(self,
|
46 |
+
unet_config,
|
47 |
+
timesteps=1000,
|
48 |
+
beta_schedule="linear",
|
49 |
+
loss_type="l2",
|
50 |
+
ckpt_path=None,
|
51 |
+
ignore_keys=None,
|
52 |
+
load_only_unet=False,
|
53 |
+
monitor="val/loss",
|
54 |
+
use_ema=True,
|
55 |
+
first_stage_key="image",
|
56 |
+
image_size=256,
|
57 |
+
channels=3,
|
58 |
+
log_every_t=100,
|
59 |
+
clip_denoised=True,
|
60 |
+
linear_start=1e-4,
|
61 |
+
linear_end=2e-2,
|
62 |
+
cosine_s=8e-3,
|
63 |
+
given_betas=None,
|
64 |
+
original_elbo_weight=0.,
|
65 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
66 |
+
l_simple_weight=1.,
|
67 |
+
conditioning_key=None,
|
68 |
+
parameterization="eps", # all assuming fixed variance schedules
|
69 |
+
scheduler_config=None,
|
70 |
+
use_positional_encodings=False,
|
71 |
+
learn_logvar=False,
|
72 |
+
logvar_init=0.,
|
73 |
+
):
|
74 |
+
super().__init__()
|
75 |
+
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
|
76 |
+
self.parameterization = parameterization
|
77 |
+
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
78 |
+
self.cond_stage_model = None
|
79 |
+
self.clip_denoised = clip_denoised
|
80 |
+
self.log_every_t = log_every_t
|
81 |
+
self.first_stage_key = first_stage_key
|
82 |
+
self.image_size = image_size # try conv?
|
83 |
+
self.channels = channels
|
84 |
+
self.use_positional_encodings = use_positional_encodings
|
85 |
+
self.model = DiffusionWrapperV1(unet_config, conditioning_key)
|
86 |
+
count_params(self.model, verbose=True)
|
87 |
+
self.use_ema = use_ema
|
88 |
+
if self.use_ema:
|
89 |
+
self.model_ema = LitEma(self.model)
|
90 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
91 |
+
|
92 |
+
self.use_scheduler = scheduler_config is not None
|
93 |
+
if self.use_scheduler:
|
94 |
+
self.scheduler_config = scheduler_config
|
95 |
+
|
96 |
+
self.v_posterior = v_posterior
|
97 |
+
self.original_elbo_weight = original_elbo_weight
|
98 |
+
self.l_simple_weight = l_simple_weight
|
99 |
+
|
100 |
+
if monitor is not None:
|
101 |
+
self.monitor = monitor
|
102 |
+
if ckpt_path is not None:
|
103 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [], only_model=load_only_unet)
|
104 |
+
|
105 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
106 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
107 |
+
|
108 |
+
self.loss_type = loss_type
|
109 |
+
|
110 |
+
self.learn_logvar = learn_logvar
|
111 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
112 |
+
if self.learn_logvar:
|
113 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
114 |
+
|
115 |
+
|
116 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
117 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
118 |
+
if exists(given_betas):
|
119 |
+
betas = given_betas
|
120 |
+
else:
|
121 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
122 |
+
cosine_s=cosine_s)
|
123 |
+
alphas = 1. - betas
|
124 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
125 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
126 |
+
|
127 |
+
timesteps, = betas.shape
|
128 |
+
self.num_timesteps = int(timesteps)
|
129 |
+
self.linear_start = linear_start
|
130 |
+
self.linear_end = linear_end
|
131 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
132 |
+
|
133 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
134 |
+
|
135 |
+
self.register_buffer('betas', to_torch(betas))
|
136 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
137 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
138 |
+
|
139 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
140 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
141 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
142 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
143 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
144 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
145 |
+
|
146 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
147 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
148 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
149 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
150 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
151 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
152 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
153 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
154 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
155 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
156 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
157 |
+
|
158 |
+
if self.parameterization == "eps":
|
159 |
+
lvlb_weights = self.betas ** 2 / (
|
160 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
161 |
+
elif self.parameterization == "x0":
|
162 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
163 |
+
else:
|
164 |
+
raise NotImplementedError("mu not supported")
|
165 |
+
# TODO how to choose this term
|
166 |
+
lvlb_weights[0] = lvlb_weights[1]
|
167 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
168 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
169 |
+
|
170 |
+
@contextmanager
|
171 |
+
def ema_scope(self, context=None):
|
172 |
+
if self.use_ema:
|
173 |
+
self.model_ema.store(self.model.parameters())
|
174 |
+
self.model_ema.copy_to(self.model)
|
175 |
+
if context is not None:
|
176 |
+
print(f"{context}: Switched to EMA weights")
|
177 |
+
try:
|
178 |
+
yield None
|
179 |
+
finally:
|
180 |
+
if self.use_ema:
|
181 |
+
self.model_ema.restore(self.model.parameters())
|
182 |
+
if context is not None:
|
183 |
+
print(f"{context}: Restored training weights")
|
184 |
+
|
185 |
+
def init_from_ckpt(self, path, ignore_keys=None, only_model=False):
|
186 |
+
sd = torch.load(path, map_location="cpu")
|
187 |
+
if "state_dict" in list(sd.keys()):
|
188 |
+
sd = sd["state_dict"]
|
189 |
+
keys = list(sd.keys())
|
190 |
+
for k in keys:
|
191 |
+
for ik in ignore_keys or []:
|
192 |
+
if k.startswith(ik):
|
193 |
+
print("Deleting key {} from state_dict.".format(k))
|
194 |
+
del sd[k]
|
195 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
196 |
+
sd, strict=False)
|
197 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
198 |
+
if missing:
|
199 |
+
print(f"Missing Keys: {missing}")
|
200 |
+
if unexpected:
|
201 |
+
print(f"Unexpected Keys: {unexpected}")
|
202 |
+
|
203 |
+
def q_mean_variance(self, x_start, t):
|
204 |
+
"""
|
205 |
+
Get the distribution q(x_t | x_0).
|
206 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
207 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
208 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
209 |
+
"""
|
210 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
211 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
212 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
213 |
+
return mean, variance, log_variance
|
214 |
+
|
215 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
216 |
+
return (
|
217 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
218 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
219 |
+
)
|
220 |
+
|
221 |
+
def q_posterior(self, x_start, x_t, t):
|
222 |
+
posterior_mean = (
|
223 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
224 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
225 |
+
)
|
226 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
227 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
228 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
229 |
+
|
230 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
231 |
+
model_out = self.model(x, t)
|
232 |
+
if self.parameterization == "eps":
|
233 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
234 |
+
elif self.parameterization == "x0":
|
235 |
+
x_recon = model_out
|
236 |
+
if clip_denoised:
|
237 |
+
x_recon.clamp_(-1., 1.)
|
238 |
+
|
239 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
240 |
+
return model_mean, posterior_variance, posterior_log_variance
|
241 |
+
|
242 |
+
@torch.no_grad()
|
243 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
244 |
+
b, *_, device = *x.shape, x.device
|
245 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
246 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
247 |
+
# no noise when t == 0
|
248 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
249 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
250 |
+
|
251 |
+
@torch.no_grad()
|
252 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
253 |
+
device = self.betas.device
|
254 |
+
b = shape[0]
|
255 |
+
img = torch.randn(shape, device=device)
|
256 |
+
intermediates = [img]
|
257 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
258 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
259 |
+
clip_denoised=self.clip_denoised)
|
260 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
261 |
+
intermediates.append(img)
|
262 |
+
if return_intermediates:
|
263 |
+
return img, intermediates
|
264 |
+
return img
|
265 |
+
|
266 |
+
@torch.no_grad()
|
267 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
268 |
+
image_size = self.image_size
|
269 |
+
channels = self.channels
|
270 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
271 |
+
return_intermediates=return_intermediates)
|
272 |
+
|
273 |
+
def q_sample(self, x_start, t, noise=None):
|
274 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
275 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
276 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
277 |
+
|
278 |
+
def get_loss(self, pred, target, mean=True):
|
279 |
+
if self.loss_type == 'l1':
|
280 |
+
loss = (target - pred).abs()
|
281 |
+
if mean:
|
282 |
+
loss = loss.mean()
|
283 |
+
elif self.loss_type == 'l2':
|
284 |
+
if mean:
|
285 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
286 |
+
else:
|
287 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
288 |
+
else:
|
289 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
290 |
+
|
291 |
+
return loss
|
292 |
+
|
293 |
+
def p_losses(self, x_start, t, noise=None):
|
294 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
295 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
296 |
+
model_out = self.model(x_noisy, t)
|
297 |
+
|
298 |
+
loss_dict = {}
|
299 |
+
if self.parameterization == "eps":
|
300 |
+
target = noise
|
301 |
+
elif self.parameterization == "x0":
|
302 |
+
target = x_start
|
303 |
+
else:
|
304 |
+
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
|
305 |
+
|
306 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
307 |
+
|
308 |
+
log_prefix = 'train' if self.training else 'val'
|
309 |
+
|
310 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
311 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
312 |
+
|
313 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
314 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
315 |
+
|
316 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
317 |
+
|
318 |
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
319 |
+
|
320 |
+
return loss, loss_dict
|
321 |
+
|
322 |
+
def forward(self, x, *args, **kwargs):
|
323 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
324 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
325 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
326 |
+
return self.p_losses(x, t, *args, **kwargs)
|
327 |
+
|
328 |
+
def get_input(self, batch, k):
|
329 |
+
x = batch[k]
|
330 |
+
if len(x.shape) == 3:
|
331 |
+
x = x[..., None]
|
332 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
333 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
334 |
+
return x
|
335 |
+
|
336 |
+
def shared_step(self, batch):
|
337 |
+
x = self.get_input(batch, self.first_stage_key)
|
338 |
+
loss, loss_dict = self(x)
|
339 |
+
return loss, loss_dict
|
340 |
+
|
341 |
+
def training_step(self, batch, batch_idx):
|
342 |
+
loss, loss_dict = self.shared_step(batch)
|
343 |
+
|
344 |
+
self.log_dict(loss_dict, prog_bar=True,
|
345 |
+
logger=True, on_step=True, on_epoch=True)
|
346 |
+
|
347 |
+
self.log("global_step", self.global_step,
|
348 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
349 |
+
|
350 |
+
if self.use_scheduler:
|
351 |
+
lr = self.optimizers().param_groups[0]['lr']
|
352 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
353 |
+
|
354 |
+
return loss
|
355 |
+
|
356 |
+
@torch.no_grad()
|
357 |
+
def validation_step(self, batch, batch_idx):
|
358 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
359 |
+
with self.ema_scope():
|
360 |
+
_, loss_dict_ema = self.shared_step(batch)
|
361 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
362 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
363 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
364 |
+
|
365 |
+
def on_train_batch_end(self, *args, **kwargs):
|
366 |
+
if self.use_ema:
|
367 |
+
self.model_ema(self.model)
|
368 |
+
|
369 |
+
def _get_rows_from_list(self, samples):
|
370 |
+
n_imgs_per_row = len(samples)
|
371 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
372 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
373 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
374 |
+
return denoise_grid
|
375 |
+
|
376 |
+
@torch.no_grad()
|
377 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
378 |
+
log = {}
|
379 |
+
x = self.get_input(batch, self.first_stage_key)
|
380 |
+
N = min(x.shape[0], N)
|
381 |
+
n_row = min(x.shape[0], n_row)
|
382 |
+
x = x.to(self.device)[:N]
|
383 |
+
log["inputs"] = x
|
384 |
+
|
385 |
+
# get diffusion row
|
386 |
+
diffusion_row = []
|
387 |
+
x_start = x[:n_row]
|
388 |
+
|
389 |
+
for t in range(self.num_timesteps):
|
390 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
391 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
392 |
+
t = t.to(self.device).long()
|
393 |
+
noise = torch.randn_like(x_start)
|
394 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
395 |
+
diffusion_row.append(x_noisy)
|
396 |
+
|
397 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
398 |
+
|
399 |
+
if sample:
|
400 |
+
# get denoise row
|
401 |
+
with self.ema_scope("Plotting"):
|
402 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
403 |
+
|
404 |
+
log["samples"] = samples
|
405 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
406 |
+
|
407 |
+
if return_keys:
|
408 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
409 |
+
return log
|
410 |
+
else:
|
411 |
+
return {key: log[key] for key in return_keys}
|
412 |
+
return log
|
413 |
+
|
414 |
+
def configure_optimizers(self):
|
415 |
+
lr = self.learning_rate
|
416 |
+
params = list(self.model.parameters())
|
417 |
+
if self.learn_logvar:
|
418 |
+
params = params + [self.logvar]
|
419 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
420 |
+
return opt
|
421 |
+
|
422 |
+
|
423 |
+
class LatentDiffusionV1(DDPMV1):
|
424 |
+
"""main class"""
|
425 |
+
def __init__(self,
|
426 |
+
first_stage_config,
|
427 |
+
cond_stage_config,
|
428 |
+
num_timesteps_cond=None,
|
429 |
+
cond_stage_key="image",
|
430 |
+
cond_stage_trainable=False,
|
431 |
+
concat_mode=True,
|
432 |
+
cond_stage_forward=None,
|
433 |
+
conditioning_key=None,
|
434 |
+
scale_factor=1.0,
|
435 |
+
scale_by_std=False,
|
436 |
+
*args, **kwargs):
|
437 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
438 |
+
self.scale_by_std = scale_by_std
|
439 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
440 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
441 |
+
if conditioning_key is None:
|
442 |
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
443 |
+
if cond_stage_config == '__is_unconditional__':
|
444 |
+
conditioning_key = None
|
445 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
446 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
447 |
+
super().__init__(*args, conditioning_key=conditioning_key, **kwargs)
|
448 |
+
self.concat_mode = concat_mode
|
449 |
+
self.cond_stage_trainable = cond_stage_trainable
|
450 |
+
self.cond_stage_key = cond_stage_key
|
451 |
+
try:
|
452 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
453 |
+
except Exception:
|
454 |
+
self.num_downs = 0
|
455 |
+
if not scale_by_std:
|
456 |
+
self.scale_factor = scale_factor
|
457 |
+
else:
|
458 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
459 |
+
self.instantiate_first_stage(first_stage_config)
|
460 |
+
self.instantiate_cond_stage(cond_stage_config)
|
461 |
+
self.cond_stage_forward = cond_stage_forward
|
462 |
+
self.clip_denoised = False
|
463 |
+
self.bbox_tokenizer = None
|
464 |
+
|
465 |
+
self.restarted_from_ckpt = False
|
466 |
+
if ckpt_path is not None:
|
467 |
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
468 |
+
self.restarted_from_ckpt = True
|
469 |
+
|
470 |
+
def make_cond_schedule(self, ):
|
471 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
472 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
473 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
474 |
+
|
475 |
+
@rank_zero_only
|
476 |
+
@torch.no_grad()
|
477 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
|
478 |
+
# only for very first batch
|
479 |
+
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
|
480 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
481 |
+
# set rescale weight to 1./std of encodings
|
482 |
+
print("### USING STD-RESCALING ###")
|
483 |
+
x = super().get_input(batch, self.first_stage_key)
|
484 |
+
x = x.to(self.device)
|
485 |
+
encoder_posterior = self.encode_first_stage(x)
|
486 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
487 |
+
del self.scale_factor
|
488 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
489 |
+
print(f"setting self.scale_factor to {self.scale_factor}")
|
490 |
+
print("### USING STD-RESCALING ###")
|
491 |
+
|
492 |
+
def register_schedule(self,
|
493 |
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
494 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
495 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
496 |
+
|
497 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
498 |
+
if self.shorten_cond_schedule:
|
499 |
+
self.make_cond_schedule()
|
500 |
+
|
501 |
+
def instantiate_first_stage(self, config):
|
502 |
+
model = instantiate_from_config(config)
|
503 |
+
self.first_stage_model = model.eval()
|
504 |
+
self.first_stage_model.train = disabled_train
|
505 |
+
for param in self.first_stage_model.parameters():
|
506 |
+
param.requires_grad = False
|
507 |
+
|
508 |
+
def instantiate_cond_stage(self, config):
|
509 |
+
if not self.cond_stage_trainable:
|
510 |
+
if config == "__is_first_stage__":
|
511 |
+
print("Using first stage also as cond stage.")
|
512 |
+
self.cond_stage_model = self.first_stage_model
|
513 |
+
elif config == "__is_unconditional__":
|
514 |
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
515 |
+
self.cond_stage_model = None
|
516 |
+
# self.be_unconditional = True
|
517 |
+
else:
|
518 |
+
model = instantiate_from_config(config)
|
519 |
+
self.cond_stage_model = model.eval()
|
520 |
+
self.cond_stage_model.train = disabled_train
|
521 |
+
for param in self.cond_stage_model.parameters():
|
522 |
+
param.requires_grad = False
|
523 |
+
else:
|
524 |
+
assert config != '__is_first_stage__'
|
525 |
+
assert config != '__is_unconditional__'
|
526 |
+
model = instantiate_from_config(config)
|
527 |
+
self.cond_stage_model = model
|
528 |
+
|
529 |
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
530 |
+
denoise_row = []
|
531 |
+
for zd in tqdm(samples, desc=desc):
|
532 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
533 |
+
force_not_quantize=force_no_decoder_quantization))
|
534 |
+
n_imgs_per_row = len(denoise_row)
|
535 |
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
536 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
537 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
538 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
539 |
+
return denoise_grid
|
540 |
+
|
541 |
+
def get_first_stage_encoding(self, encoder_posterior):
|
542 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
543 |
+
z = encoder_posterior.sample()
|
544 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
545 |
+
z = encoder_posterior
|
546 |
+
else:
|
547 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
548 |
+
return self.scale_factor * z
|
549 |
+
|
550 |
+
def get_learned_conditioning(self, c):
|
551 |
+
if self.cond_stage_forward is None:
|
552 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
553 |
+
c = self.cond_stage_model.encode(c)
|
554 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
555 |
+
c = c.mode()
|
556 |
+
else:
|
557 |
+
c = self.cond_stage_model(c)
|
558 |
+
else:
|
559 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
560 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
561 |
+
return c
|
562 |
+
|
563 |
+
def meshgrid(self, h, w):
|
564 |
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
565 |
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
566 |
+
|
567 |
+
arr = torch.cat([y, x], dim=-1)
|
568 |
+
return arr
|
569 |
+
|
570 |
+
def delta_border(self, h, w):
|
571 |
+
"""
|
572 |
+
:param h: height
|
573 |
+
:param w: width
|
574 |
+
:return: normalized distance to image border,
|
575 |
+
with min distance = 0 at border and max dist = 0.5 at image center
|
576 |
+
"""
|
577 |
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
578 |
+
arr = self.meshgrid(h, w) / lower_right_corner
|
579 |
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
580 |
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
581 |
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
582 |
+
return edge_dist
|
583 |
+
|
584 |
+
def get_weighting(self, h, w, Ly, Lx, device):
|
585 |
+
weighting = self.delta_border(h, w)
|
586 |
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
587 |
+
self.split_input_params["clip_max_weight"], )
|
588 |
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
589 |
+
|
590 |
+
if self.split_input_params["tie_braker"]:
|
591 |
+
L_weighting = self.delta_border(Ly, Lx)
|
592 |
+
L_weighting = torch.clip(L_weighting,
|
593 |
+
self.split_input_params["clip_min_tie_weight"],
|
594 |
+
self.split_input_params["clip_max_tie_weight"])
|
595 |
+
|
596 |
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
597 |
+
weighting = weighting * L_weighting
|
598 |
+
return weighting
|
599 |
+
|
600 |
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
601 |
+
"""
|
602 |
+
:param x: img of size (bs, c, h, w)
|
603 |
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
604 |
+
"""
|
605 |
+
bs, nc, h, w = x.shape
|
606 |
+
|
607 |
+
# number of crops in image
|
608 |
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
609 |
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
610 |
+
|
611 |
+
if uf == 1 and df == 1:
|
612 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
613 |
+
unfold = torch.nn.Unfold(**fold_params)
|
614 |
+
|
615 |
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
616 |
+
|
617 |
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
618 |
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
619 |
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
620 |
+
|
621 |
+
elif uf > 1 and df == 1:
|
622 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
623 |
+
unfold = torch.nn.Unfold(**fold_params)
|
624 |
+
|
625 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
626 |
+
dilation=1, padding=0,
|
627 |
+
stride=(stride[0] * uf, stride[1] * uf))
|
628 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
629 |
+
|
630 |
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
631 |
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
632 |
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
633 |
+
|
634 |
+
elif df > 1 and uf == 1:
|
635 |
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
636 |
+
unfold = torch.nn.Unfold(**fold_params)
|
637 |
+
|
638 |
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
639 |
+
dilation=1, padding=0,
|
640 |
+
stride=(stride[0] // df, stride[1] // df))
|
641 |
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
642 |
+
|
643 |
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
644 |
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
645 |
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
646 |
+
|
647 |
+
else:
|
648 |
+
raise NotImplementedError
|
649 |
+
|
650 |
+
return fold, unfold, normalization, weighting
|
651 |
+
|
652 |
+
@torch.no_grad()
|
653 |
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
654 |
+
cond_key=None, return_original_cond=False, bs=None):
|
655 |
+
x = super().get_input(batch, k)
|
656 |
+
if bs is not None:
|
657 |
+
x = x[:bs]
|
658 |
+
x = x.to(self.device)
|
659 |
+
encoder_posterior = self.encode_first_stage(x)
|
660 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
661 |
+
|
662 |
+
if self.model.conditioning_key is not None:
|
663 |
+
if cond_key is None:
|
664 |
+
cond_key = self.cond_stage_key
|
665 |
+
if cond_key != self.first_stage_key:
|
666 |
+
if cond_key in ['caption', 'coordinates_bbox']:
|
667 |
+
xc = batch[cond_key]
|
668 |
+
elif cond_key == 'class_label':
|
669 |
+
xc = batch
|
670 |
+
else:
|
671 |
+
xc = super().get_input(batch, cond_key).to(self.device)
|
672 |
+
else:
|
673 |
+
xc = x
|
674 |
+
if not self.cond_stage_trainable or force_c_encode:
|
675 |
+
if isinstance(xc, dict) or isinstance(xc, list):
|
676 |
+
# import pudb; pudb.set_trace()
|
677 |
+
c = self.get_learned_conditioning(xc)
|
678 |
+
else:
|
679 |
+
c = self.get_learned_conditioning(xc.to(self.device))
|
680 |
+
else:
|
681 |
+
c = xc
|
682 |
+
if bs is not None:
|
683 |
+
c = c[:bs]
|
684 |
+
|
685 |
+
if self.use_positional_encodings:
|
686 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
687 |
+
ckey = __conditioning_keys__[self.model.conditioning_key]
|
688 |
+
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
|
689 |
+
|
690 |
+
else:
|
691 |
+
c = None
|
692 |
+
xc = None
|
693 |
+
if self.use_positional_encodings:
|
694 |
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
695 |
+
c = {'pos_x': pos_x, 'pos_y': pos_y}
|
696 |
+
out = [z, c]
|
697 |
+
if return_first_stage_outputs:
|
698 |
+
xrec = self.decode_first_stage(z)
|
699 |
+
out.extend([x, xrec])
|
700 |
+
if return_original_cond:
|
701 |
+
out.append(xc)
|
702 |
+
return out
|
703 |
+
|
704 |
+
@torch.no_grad()
|
705 |
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
706 |
+
if predict_cids:
|
707 |
+
if z.dim() == 4:
|
708 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
709 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
710 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
711 |
+
|
712 |
+
z = 1. / self.scale_factor * z
|
713 |
+
|
714 |
+
if hasattr(self, "split_input_params"):
|
715 |
+
if self.split_input_params["patch_distributed_vq"]:
|
716 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
717 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
718 |
+
uf = self.split_input_params["vqf"]
|
719 |
+
bs, nc, h, w = z.shape
|
720 |
+
if ks[0] > h or ks[1] > w:
|
721 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
722 |
+
print("reducing Kernel")
|
723 |
+
|
724 |
+
if stride[0] > h or stride[1] > w:
|
725 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
726 |
+
print("reducing stride")
|
727 |
+
|
728 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
|
729 |
+
|
730 |
+
z = unfold(z) # (bn, nc * prod(**ks), L)
|
731 |
+
# 1. Reshape to img shape
|
732 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
733 |
+
|
734 |
+
# 2. apply model loop over last dim
|
735 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
736 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
737 |
+
force_not_quantize=predict_cids or force_not_quantize)
|
738 |
+
for i in range(z.shape[-1])]
|
739 |
+
else:
|
740 |
+
|
741 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
|
742 |
+
for i in range(z.shape[-1])]
|
743 |
+
|
744 |
+
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
|
745 |
+
o = o * weighting
|
746 |
+
# Reverse 1. reshape to img shape
|
747 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
748 |
+
# stitch crops together
|
749 |
+
decoded = fold(o)
|
750 |
+
decoded = decoded / normalization # norm is shape (1, 1, h, w)
|
751 |
+
return decoded
|
752 |
+
else:
|
753 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
754 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
755 |
+
else:
|
756 |
+
return self.first_stage_model.decode(z)
|
757 |
+
|
758 |
+
else:
|
759 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
760 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
761 |
+
else:
|
762 |
+
return self.first_stage_model.decode(z)
|
763 |
+
|
764 |
+
# same as above but without decorator
|
765 |
+
def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
766 |
+
if predict_cids:
|
767 |
+
if z.dim() == 4:
|
768 |
+
z = torch.argmax(z.exp(), dim=1).long()
|
769 |
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
770 |
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
771 |
+
|
772 |
+
z = 1. / self.scale_factor * z
|
773 |
+
|
774 |
+
if hasattr(self, "split_input_params"):
|
775 |
+
if self.split_input_params["patch_distributed_vq"]:
|
776 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
777 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
778 |
+
uf = self.split_input_params["vqf"]
|
779 |
+
bs, nc, h, w = z.shape
|
780 |
+
if ks[0] > h or ks[1] > w:
|
781 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
782 |
+
print("reducing Kernel")
|
783 |
+
|
784 |
+
if stride[0] > h or stride[1] > w:
|
785 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
786 |
+
print("reducing stride")
|
787 |
+
|
788 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
|
789 |
+
|
790 |
+
z = unfold(z) # (bn, nc * prod(**ks), L)
|
791 |
+
# 1. Reshape to img shape
|
792 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
793 |
+
|
794 |
+
# 2. apply model loop over last dim
|
795 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
796 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
|
797 |
+
force_not_quantize=predict_cids or force_not_quantize)
|
798 |
+
for i in range(z.shape[-1])]
|
799 |
+
else:
|
800 |
+
|
801 |
+
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
|
802 |
+
for i in range(z.shape[-1])]
|
803 |
+
|
804 |
+
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
|
805 |
+
o = o * weighting
|
806 |
+
# Reverse 1. reshape to img shape
|
807 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
808 |
+
# stitch crops together
|
809 |
+
decoded = fold(o)
|
810 |
+
decoded = decoded / normalization # norm is shape (1, 1, h, w)
|
811 |
+
return decoded
|
812 |
+
else:
|
813 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
814 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
815 |
+
else:
|
816 |
+
return self.first_stage_model.decode(z)
|
817 |
+
|
818 |
+
else:
|
819 |
+
if isinstance(self.first_stage_model, VQModelInterface):
|
820 |
+
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
|
821 |
+
else:
|
822 |
+
return self.first_stage_model.decode(z)
|
823 |
+
|
824 |
+
@torch.no_grad()
|
825 |
+
def encode_first_stage(self, x):
|
826 |
+
if hasattr(self, "split_input_params"):
|
827 |
+
if self.split_input_params["patch_distributed_vq"]:
|
828 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
829 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
830 |
+
df = self.split_input_params["vqf"]
|
831 |
+
self.split_input_params['original_image_size'] = x.shape[-2:]
|
832 |
+
bs, nc, h, w = x.shape
|
833 |
+
if ks[0] > h or ks[1] > w:
|
834 |
+
ks = (min(ks[0], h), min(ks[1], w))
|
835 |
+
print("reducing Kernel")
|
836 |
+
|
837 |
+
if stride[0] > h or stride[1] > w:
|
838 |
+
stride = (min(stride[0], h), min(stride[1], w))
|
839 |
+
print("reducing stride")
|
840 |
+
|
841 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
|
842 |
+
z = unfold(x) # (bn, nc * prod(**ks), L)
|
843 |
+
# Reshape to img shape
|
844 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
845 |
+
|
846 |
+
output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
|
847 |
+
for i in range(z.shape[-1])]
|
848 |
+
|
849 |
+
o = torch.stack(output_list, axis=-1)
|
850 |
+
o = o * weighting
|
851 |
+
|
852 |
+
# Reverse reshape to img shape
|
853 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
854 |
+
# stitch crops together
|
855 |
+
decoded = fold(o)
|
856 |
+
decoded = decoded / normalization
|
857 |
+
return decoded
|
858 |
+
|
859 |
+
else:
|
860 |
+
return self.first_stage_model.encode(x)
|
861 |
+
else:
|
862 |
+
return self.first_stage_model.encode(x)
|
863 |
+
|
864 |
+
def shared_step(self, batch, **kwargs):
|
865 |
+
x, c = self.get_input(batch, self.first_stage_key)
|
866 |
+
loss = self(x, c)
|
867 |
+
return loss
|
868 |
+
|
869 |
+
def forward(self, x, c, *args, **kwargs):
|
870 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
871 |
+
if self.model.conditioning_key is not None:
|
872 |
+
assert c is not None
|
873 |
+
if self.cond_stage_trainable:
|
874 |
+
c = self.get_learned_conditioning(c)
|
875 |
+
if self.shorten_cond_schedule: # TODO: drop this option
|
876 |
+
tc = self.cond_ids[t].to(self.device)
|
877 |
+
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
|
878 |
+
return self.p_losses(x, c, t, *args, **kwargs)
|
879 |
+
|
880 |
+
def apply_model(self, x_noisy, t, cond, return_ids=False):
|
881 |
+
|
882 |
+
if isinstance(cond, dict):
|
883 |
+
# hybrid case, cond is expected to be a dict
|
884 |
+
pass
|
885 |
+
else:
|
886 |
+
if not isinstance(cond, list):
|
887 |
+
cond = [cond]
|
888 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
889 |
+
cond = {key: cond}
|
890 |
+
|
891 |
+
if hasattr(self, "split_input_params"):
|
892 |
+
assert len(cond) == 1 # todo can only deal with one conditioning atm
|
893 |
+
assert not return_ids
|
894 |
+
ks = self.split_input_params["ks"] # eg. (128, 128)
|
895 |
+
stride = self.split_input_params["stride"] # eg. (64, 64)
|
896 |
+
|
897 |
+
h, w = x_noisy.shape[-2:]
|
898 |
+
|
899 |
+
fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
|
900 |
+
|
901 |
+
z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
|
902 |
+
# Reshape to img shape
|
903 |
+
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
904 |
+
z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
|
905 |
+
|
906 |
+
if self.cond_stage_key in ["image", "LR_image", "segmentation",
|
907 |
+
'bbox_img'] and self.model.conditioning_key: # todo check for completeness
|
908 |
+
c_key = next(iter(cond.keys())) # get key
|
909 |
+
c = next(iter(cond.values())) # get value
|
910 |
+
assert (len(c) == 1) # todo extend to list with more than one elem
|
911 |
+
c = c[0] # get element
|
912 |
+
|
913 |
+
c = unfold(c)
|
914 |
+
c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
|
915 |
+
|
916 |
+
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
|
917 |
+
|
918 |
+
elif self.cond_stage_key == 'coordinates_bbox':
|
919 |
+
assert 'original_image_size' in self.split_input_params, 'BoundingBoxRescaling is missing original_image_size'
|
920 |
+
|
921 |
+
# assuming padding of unfold is always 0 and its dilation is always 1
|
922 |
+
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
|
923 |
+
full_img_h, full_img_w = self.split_input_params['original_image_size']
|
924 |
+
# as we are operating on latents, we need the factor from the original image size to the
|
925 |
+
# spatial latent size to properly rescale the crops for regenerating the bbox annotations
|
926 |
+
num_downs = self.first_stage_model.encoder.num_resolutions - 1
|
927 |
+
rescale_latent = 2 ** (num_downs)
|
928 |
+
|
929 |
+
# get top left positions of patches as conforming for the bbbox tokenizer, therefore we
|
930 |
+
# need to rescale the tl patch coordinates to be in between (0,1)
|
931 |
+
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
|
932 |
+
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
|
933 |
+
for patch_nr in range(z.shape[-1])]
|
934 |
+
|
935 |
+
# patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
|
936 |
+
patch_limits = [(x_tl, y_tl,
|
937 |
+
rescale_latent * ks[0] / full_img_w,
|
938 |
+
rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
|
939 |
+
# patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
|
940 |
+
|
941 |
+
# tokenize crop coordinates for the bounding boxes of the respective patches
|
942 |
+
patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
|
943 |
+
for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
|
944 |
+
print(patch_limits_tknzd[0].shape)
|
945 |
+
# cut tknzd crop position from conditioning
|
946 |
+
assert isinstance(cond, dict), 'cond must be dict to be fed into model'
|
947 |
+
cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
|
948 |
+
print(cut_cond.shape)
|
949 |
+
|
950 |
+
adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
|
951 |
+
adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
|
952 |
+
print(adapted_cond.shape)
|
953 |
+
adapted_cond = self.get_learned_conditioning(adapted_cond)
|
954 |
+
print(adapted_cond.shape)
|
955 |
+
adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
|
956 |
+
print(adapted_cond.shape)
|
957 |
+
|
958 |
+
cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
|
959 |
+
|
960 |
+
else:
|
961 |
+
cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
|
962 |
+
|
963 |
+
# apply model by loop over crops
|
964 |
+
output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
|
965 |
+
assert not isinstance(output_list[0],
|
966 |
+
tuple) # todo cant deal with multiple model outputs check this never happens
|
967 |
+
|
968 |
+
o = torch.stack(output_list, axis=-1)
|
969 |
+
o = o * weighting
|
970 |
+
# Reverse reshape to img shape
|
971 |
+
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
|
972 |
+
# stitch crops together
|
973 |
+
x_recon = fold(o) / normalization
|
974 |
+
|
975 |
+
else:
|
976 |
+
x_recon = self.model(x_noisy, t, **cond)
|
977 |
+
|
978 |
+
if isinstance(x_recon, tuple) and not return_ids:
|
979 |
+
return x_recon[0]
|
980 |
+
else:
|
981 |
+
return x_recon
|
982 |
+
|
983 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
984 |
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
985 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
986 |
+
|
987 |
+
def _prior_bpd(self, x_start):
|
988 |
+
"""
|
989 |
+
Get the prior KL term for the variational lower-bound, measured in
|
990 |
+
bits-per-dim.
|
991 |
+
This term can't be optimized, as it only depends on the encoder.
|
992 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
993 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
994 |
+
"""
|
995 |
+
batch_size = x_start.shape[0]
|
996 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
997 |
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
998 |
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
999 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
1000 |
+
|
1001 |
+
def p_losses(self, x_start, cond, t, noise=None):
|
1002 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
1003 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
1004 |
+
model_output = self.apply_model(x_noisy, t, cond)
|
1005 |
+
|
1006 |
+
loss_dict = {}
|
1007 |
+
prefix = 'train' if self.training else 'val'
|
1008 |
+
|
1009 |
+
if self.parameterization == "x0":
|
1010 |
+
target = x_start
|
1011 |
+
elif self.parameterization == "eps":
|
1012 |
+
target = noise
|
1013 |
+
else:
|
1014 |
+
raise NotImplementedError()
|
1015 |
+
|
1016 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
1017 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
1018 |
+
|
1019 |
+
logvar_t = self.logvar[t].to(self.device)
|
1020 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
1021 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
1022 |
+
if self.learn_logvar:
|
1023 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
1024 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
1025 |
+
|
1026 |
+
loss = self.l_simple_weight * loss.mean()
|
1027 |
+
|
1028 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
1029 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
1030 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
1031 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
1032 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
1033 |
+
|
1034 |
+
return loss, loss_dict
|
1035 |
+
|
1036 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
1037 |
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
1038 |
+
t_in = t
|
1039 |
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
1040 |
+
|
1041 |
+
if score_corrector is not None:
|
1042 |
+
assert self.parameterization == "eps"
|
1043 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
1044 |
+
|
1045 |
+
if return_codebook_ids:
|
1046 |
+
model_out, logits = model_out
|
1047 |
+
|
1048 |
+
if self.parameterization == "eps":
|
1049 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
1050 |
+
elif self.parameterization == "x0":
|
1051 |
+
x_recon = model_out
|
1052 |
+
else:
|
1053 |
+
raise NotImplementedError()
|
1054 |
+
|
1055 |
+
if clip_denoised:
|
1056 |
+
x_recon.clamp_(-1., 1.)
|
1057 |
+
if quantize_denoised:
|
1058 |
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
1059 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
1060 |
+
if return_codebook_ids:
|
1061 |
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
1062 |
+
elif return_x0:
|
1063 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
1064 |
+
else:
|
1065 |
+
return model_mean, posterior_variance, posterior_log_variance
|
1066 |
+
|
1067 |
+
@torch.no_grad()
|
1068 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
1069 |
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
1070 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
1071 |
+
b, *_, device = *x.shape, x.device
|
1072 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
1073 |
+
return_codebook_ids=return_codebook_ids,
|
1074 |
+
quantize_denoised=quantize_denoised,
|
1075 |
+
return_x0=return_x0,
|
1076 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1077 |
+
if return_codebook_ids:
|
1078 |
+
raise DeprecationWarning("Support dropped.")
|
1079 |
+
model_mean, _, model_log_variance, logits = outputs
|
1080 |
+
elif return_x0:
|
1081 |
+
model_mean, _, model_log_variance, x0 = outputs
|
1082 |
+
else:
|
1083 |
+
model_mean, _, model_log_variance = outputs
|
1084 |
+
|
1085 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
1086 |
+
if noise_dropout > 0.:
|
1087 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
1088 |
+
# no noise when t == 0
|
1089 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
1090 |
+
|
1091 |
+
if return_codebook_ids:
|
1092 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
1093 |
+
if return_x0:
|
1094 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
1095 |
+
else:
|
1096 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
1097 |
+
|
1098 |
+
@torch.no_grad()
|
1099 |
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
1100 |
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
1101 |
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
1102 |
+
log_every_t=None):
|
1103 |
+
if not log_every_t:
|
1104 |
+
log_every_t = self.log_every_t
|
1105 |
+
timesteps = self.num_timesteps
|
1106 |
+
if batch_size is not None:
|
1107 |
+
b = batch_size if batch_size is not None else shape[0]
|
1108 |
+
shape = [batch_size] + list(shape)
|
1109 |
+
else:
|
1110 |
+
b = batch_size = shape[0]
|
1111 |
+
if x_T is None:
|
1112 |
+
img = torch.randn(shape, device=self.device)
|
1113 |
+
else:
|
1114 |
+
img = x_T
|
1115 |
+
intermediates = []
|
1116 |
+
if cond is not None:
|
1117 |
+
if isinstance(cond, dict):
|
1118 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1119 |
+
[x[:batch_size] for x in cond[key]] for key in cond}
|
1120 |
+
else:
|
1121 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1122 |
+
|
1123 |
+
if start_T is not None:
|
1124 |
+
timesteps = min(timesteps, start_T)
|
1125 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
1126 |
+
total=timesteps) if verbose else reversed(
|
1127 |
+
range(0, timesteps))
|
1128 |
+
if type(temperature) == float:
|
1129 |
+
temperature = [temperature] * timesteps
|
1130 |
+
|
1131 |
+
for i in iterator:
|
1132 |
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
1133 |
+
if self.shorten_cond_schedule:
|
1134 |
+
assert self.model.conditioning_key != 'hybrid'
|
1135 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1136 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1137 |
+
|
1138 |
+
img, x0_partial = self.p_sample(img, cond, ts,
|
1139 |
+
clip_denoised=self.clip_denoised,
|
1140 |
+
quantize_denoised=quantize_denoised, return_x0=True,
|
1141 |
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
1142 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
1143 |
+
if mask is not None:
|
1144 |
+
assert x0 is not None
|
1145 |
+
img_orig = self.q_sample(x0, ts)
|
1146 |
+
img = img_orig * mask + (1. - mask) * img
|
1147 |
+
|
1148 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1149 |
+
intermediates.append(x0_partial)
|
1150 |
+
if callback:
|
1151 |
+
callback(i)
|
1152 |
+
if img_callback:
|
1153 |
+
img_callback(img, i)
|
1154 |
+
return img, intermediates
|
1155 |
+
|
1156 |
+
@torch.no_grad()
|
1157 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
1158 |
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
1159 |
+
mask=None, x0=None, img_callback=None, start_T=None,
|
1160 |
+
log_every_t=None):
|
1161 |
+
|
1162 |
+
if not log_every_t:
|
1163 |
+
log_every_t = self.log_every_t
|
1164 |
+
device = self.betas.device
|
1165 |
+
b = shape[0]
|
1166 |
+
if x_T is None:
|
1167 |
+
img = torch.randn(shape, device=device)
|
1168 |
+
else:
|
1169 |
+
img = x_T
|
1170 |
+
|
1171 |
+
intermediates = [img]
|
1172 |
+
if timesteps is None:
|
1173 |
+
timesteps = self.num_timesteps
|
1174 |
+
|
1175 |
+
if start_T is not None:
|
1176 |
+
timesteps = min(timesteps, start_T)
|
1177 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
1178 |
+
range(0, timesteps))
|
1179 |
+
|
1180 |
+
if mask is not None:
|
1181 |
+
assert x0 is not None
|
1182 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
1183 |
+
|
1184 |
+
for i in iterator:
|
1185 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
1186 |
+
if self.shorten_cond_schedule:
|
1187 |
+
assert self.model.conditioning_key != 'hybrid'
|
1188 |
+
tc = self.cond_ids[ts].to(cond.device)
|
1189 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
1190 |
+
|
1191 |
+
img = self.p_sample(img, cond, ts,
|
1192 |
+
clip_denoised=self.clip_denoised,
|
1193 |
+
quantize_denoised=quantize_denoised)
|
1194 |
+
if mask is not None:
|
1195 |
+
img_orig = self.q_sample(x0, ts)
|
1196 |
+
img = img_orig * mask + (1. - mask) * img
|
1197 |
+
|
1198 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
1199 |
+
intermediates.append(img)
|
1200 |
+
if callback:
|
1201 |
+
callback(i)
|
1202 |
+
if img_callback:
|
1203 |
+
img_callback(img, i)
|
1204 |
+
|
1205 |
+
if return_intermediates:
|
1206 |
+
return img, intermediates
|
1207 |
+
return img
|
1208 |
+
|
1209 |
+
@torch.no_grad()
|
1210 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
1211 |
+
verbose=True, timesteps=None, quantize_denoised=False,
|
1212 |
+
mask=None, x0=None, shape=None,**kwargs):
|
1213 |
+
if shape is None:
|
1214 |
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
1215 |
+
if cond is not None:
|
1216 |
+
if isinstance(cond, dict):
|
1217 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
1218 |
+
[x[:batch_size] for x in cond[key]] for key in cond}
|
1219 |
+
else:
|
1220 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
1221 |
+
return self.p_sample_loop(cond,
|
1222 |
+
shape,
|
1223 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1224 |
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
1225 |
+
mask=mask, x0=x0)
|
1226 |
+
|
1227 |
+
@torch.no_grad()
|
1228 |
+
def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
|
1229 |
+
|
1230 |
+
if ddim:
|
1231 |
+
ddim_sampler = DDIMSampler(self)
|
1232 |
+
shape = (self.channels, self.image_size, self.image_size)
|
1233 |
+
samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
|
1234 |
+
shape,cond,verbose=False,**kwargs)
|
1235 |
+
|
1236 |
+
else:
|
1237 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
1238 |
+
return_intermediates=True,**kwargs)
|
1239 |
+
|
1240 |
+
return samples, intermediates
|
1241 |
+
|
1242 |
+
|
1243 |
+
@torch.no_grad()
|
1244 |
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
|
1245 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
1246 |
+
plot_diffusion_rows=True, **kwargs):
|
1247 |
+
|
1248 |
+
use_ddim = ddim_steps is not None
|
1249 |
+
|
1250 |
+
log = {}
|
1251 |
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
1252 |
+
return_first_stage_outputs=True,
|
1253 |
+
force_c_encode=True,
|
1254 |
+
return_original_cond=True,
|
1255 |
+
bs=N)
|
1256 |
+
N = min(x.shape[0], N)
|
1257 |
+
n_row = min(x.shape[0], n_row)
|
1258 |
+
log["inputs"] = x
|
1259 |
+
log["reconstruction"] = xrec
|
1260 |
+
if self.model.conditioning_key is not None:
|
1261 |
+
if hasattr(self.cond_stage_model, "decode"):
|
1262 |
+
xc = self.cond_stage_model.decode(c)
|
1263 |
+
log["conditioning"] = xc
|
1264 |
+
elif self.cond_stage_key in ["caption"]:
|
1265 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
|
1266 |
+
log["conditioning"] = xc
|
1267 |
+
elif self.cond_stage_key == 'class_label':
|
1268 |
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
|
1269 |
+
log['conditioning'] = xc
|
1270 |
+
elif isimage(xc):
|
1271 |
+
log["conditioning"] = xc
|
1272 |
+
if ismap(xc):
|
1273 |
+
log["original_conditioning"] = self.to_rgb(xc)
|
1274 |
+
|
1275 |
+
if plot_diffusion_rows:
|
1276 |
+
# get diffusion row
|
1277 |
+
diffusion_row = []
|
1278 |
+
z_start = z[:n_row]
|
1279 |
+
for t in range(self.num_timesteps):
|
1280 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
1281 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
1282 |
+
t = t.to(self.device).long()
|
1283 |
+
noise = torch.randn_like(z_start)
|
1284 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
1285 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
1286 |
+
|
1287 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
1288 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
1289 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
1290 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
1291 |
+
log["diffusion_row"] = diffusion_grid
|
1292 |
+
|
1293 |
+
if sample:
|
1294 |
+
# get denoise row
|
1295 |
+
with self.ema_scope("Plotting"):
|
1296 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1297 |
+
ddim_steps=ddim_steps,eta=ddim_eta)
|
1298 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
1299 |
+
x_samples = self.decode_first_stage(samples)
|
1300 |
+
log["samples"] = x_samples
|
1301 |
+
if plot_denoise_rows:
|
1302 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1303 |
+
log["denoise_row"] = denoise_grid
|
1304 |
+
|
1305 |
+
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
1306 |
+
self.first_stage_model, IdentityFirstStage):
|
1307 |
+
# also display when quantizing x0 while sampling
|
1308 |
+
with self.ema_scope("Plotting Quantized Denoised"):
|
1309 |
+
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
|
1310 |
+
ddim_steps=ddim_steps,eta=ddim_eta,
|
1311 |
+
quantize_denoised=True)
|
1312 |
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
1313 |
+
# quantize_denoised=True)
|
1314 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1315 |
+
log["samples_x0_quantized"] = x_samples
|
1316 |
+
|
1317 |
+
if inpaint:
|
1318 |
+
# make a simple center square
|
1319 |
+
h, w = z.shape[2], z.shape[3]
|
1320 |
+
mask = torch.ones(N, h, w).to(self.device)
|
1321 |
+
# zeros will be filled in
|
1322 |
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
1323 |
+
mask = mask[:, None, ...]
|
1324 |
+
with self.ema_scope("Plotting Inpaint"):
|
1325 |
+
|
1326 |
+
samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
|
1327 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1328 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1329 |
+
log["samples_inpainting"] = x_samples
|
1330 |
+
log["mask"] = mask
|
1331 |
+
|
1332 |
+
# outpaint
|
1333 |
+
with self.ema_scope("Plotting Outpaint"):
|
1334 |
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
|
1335 |
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
1336 |
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
1337 |
+
log["samples_outpainting"] = x_samples
|
1338 |
+
|
1339 |
+
if plot_progressive_rows:
|
1340 |
+
with self.ema_scope("Plotting Progressives"):
|
1341 |
+
img, progressives = self.progressive_denoising(c,
|
1342 |
+
shape=(self.channels, self.image_size, self.image_size),
|
1343 |
+
batch_size=N)
|
1344 |
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
1345 |
+
log["progressive_row"] = prog_row
|
1346 |
+
|
1347 |
+
if return_keys:
|
1348 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
1349 |
+
return log
|
1350 |
+
else:
|
1351 |
+
return {key: log[key] for key in return_keys}
|
1352 |
+
return log
|
1353 |
+
|
1354 |
+
def configure_optimizers(self):
|
1355 |
+
lr = self.learning_rate
|
1356 |
+
params = list(self.model.parameters())
|
1357 |
+
if self.cond_stage_trainable:
|
1358 |
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
1359 |
+
params = params + list(self.cond_stage_model.parameters())
|
1360 |
+
if self.learn_logvar:
|
1361 |
+
print('Diffusion model optimizing logvar')
|
1362 |
+
params.append(self.logvar)
|
1363 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
1364 |
+
if self.use_scheduler:
|
1365 |
+
assert 'target' in self.scheduler_config
|
1366 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1367 |
+
|
1368 |
+
print("Setting up LambdaLR scheduler...")
|
1369 |
+
scheduler = [
|
1370 |
+
{
|
1371 |
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
1372 |
+
'interval': 'step',
|
1373 |
+
'frequency': 1
|
1374 |
+
}]
|
1375 |
+
return [opt], scheduler
|
1376 |
+
return opt
|
1377 |
+
|
1378 |
+
@torch.no_grad()
|
1379 |
+
def to_rgb(self, x):
|
1380 |
+
x = x.float()
|
1381 |
+
if not hasattr(self, "colorize"):
|
1382 |
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
1383 |
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
1384 |
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
1385 |
+
return x
|
1386 |
+
|
1387 |
+
|
1388 |
+
class DiffusionWrapperV1(pl.LightningModule):
|
1389 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1390 |
+
super().__init__()
|
1391 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1392 |
+
self.conditioning_key = conditioning_key
|
1393 |
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
|
1394 |
+
|
1395 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
|
1396 |
+
if self.conditioning_key is None:
|
1397 |
+
out = self.diffusion_model(x, t)
|
1398 |
+
elif self.conditioning_key == 'concat':
|
1399 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1400 |
+
out = self.diffusion_model(xc, t)
|
1401 |
+
elif self.conditioning_key == 'crossattn':
|
1402 |
+
cc = torch.cat(c_crossattn, 1)
|
1403 |
+
out = self.diffusion_model(x, t, context=cc)
|
1404 |
+
elif self.conditioning_key == 'hybrid':
|
1405 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1406 |
+
cc = torch.cat(c_crossattn, 1)
|
1407 |
+
out = self.diffusion_model(xc, t, context=cc)
|
1408 |
+
elif self.conditioning_key == 'adm':
|
1409 |
+
cc = c_crossattn[0]
|
1410 |
+
out = self.diffusion_model(x, t, y=cc)
|
1411 |
+
else:
|
1412 |
+
raise NotImplementedError()
|
1413 |
+
|
1414 |
+
return out
|
1415 |
+
|
1416 |
+
|
1417 |
+
class Layout2ImgDiffusionV1(LatentDiffusionV1):
|
1418 |
+
# TODO: move all layout-specific hacks to this class
|
1419 |
+
def __init__(self, cond_stage_key, *args, **kwargs):
|
1420 |
+
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
|
1421 |
+
super().__init__(*args, cond_stage_key=cond_stage_key, **kwargs)
|
1422 |
+
|
1423 |
+
def log_images(self, batch, N=8, *args, **kwargs):
|
1424 |
+
logs = super().log_images(*args, batch=batch, N=N, **kwargs)
|
1425 |
+
|
1426 |
+
key = 'train' if self.training else 'validation'
|
1427 |
+
dset = self.trainer.datamodule.datasets[key]
|
1428 |
+
mapper = dset.conditional_builders[self.cond_stage_key]
|
1429 |
+
|
1430 |
+
bbox_imgs = []
|
1431 |
+
map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
|
1432 |
+
for tknzd_bbox in batch[self.cond_stage_key][:N]:
|
1433 |
+
bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
|
1434 |
+
bbox_imgs.append(bboximg)
|
1435 |
+
|
1436 |
+
cond_img = torch.stack(bbox_imgs, dim=0)
|
1437 |
+
logs['bbox_image'] = cond_img
|
1438 |
+
return logs
|
1439 |
+
|
1440 |
+
ldm.models.diffusion.ddpm.DDPMV1 = DDPMV1
|
1441 |
+
ldm.models.diffusion.ddpm.LatentDiffusionV1 = LatentDiffusionV1
|
1442 |
+
ldm.models.diffusion.ddpm.DiffusionWrapperV1 = DiffusionWrapperV1
|
1443 |
+
ldm.models.diffusion.ddpm.Layout2ImgDiffusionV1 = Layout2ImgDiffusionV1
|
extensions-builtin/LDSR/vqvae_quantize.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Vendored from https://raw.githubusercontent.com/CompVis/taming-transformers/24268930bf1dce879235a7fddd0b2355b84d7ea6/taming/modules/vqvae/quantize.py,
|
2 |
+
# where the license is as follows:
|
3 |
+
#
|
4 |
+
# Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
|
5 |
+
#
|
6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
8 |
+
# in the Software without restriction, including without limitation the rights
|
9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
11 |
+
# furnished to do so, subject to the following conditions:
|
12 |
+
#
|
13 |
+
# The above copyright notice and this permission notice shall be included in all
|
14 |
+
# copies or substantial portions of the Software.
|
15 |
+
#
|
16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
17 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
18 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
19 |
+
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
20 |
+
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
21 |
+
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
22 |
+
# OR OTHER DEALINGS IN THE SOFTWARE./
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn as nn
|
26 |
+
import numpy as np
|
27 |
+
from einops import rearrange
|
28 |
+
|
29 |
+
|
30 |
+
class VectorQuantizer2(nn.Module):
|
31 |
+
"""
|
32 |
+
Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly
|
33 |
+
avoids costly matrix multiplications and allows for post-hoc remapping of indices.
|
34 |
+
"""
|
35 |
+
|
36 |
+
# NOTE: due to a bug the beta term was applied to the wrong term. for
|
37 |
+
# backwards compatibility we use the buggy version by default, but you can
|
38 |
+
# specify legacy=False to fix it.
|
39 |
+
def __init__(self, n_e, e_dim, beta, remap=None, unknown_index="random",
|
40 |
+
sane_index_shape=False, legacy=True):
|
41 |
+
super().__init__()
|
42 |
+
self.n_e = n_e
|
43 |
+
self.e_dim = e_dim
|
44 |
+
self.beta = beta
|
45 |
+
self.legacy = legacy
|
46 |
+
|
47 |
+
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
48 |
+
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
49 |
+
|
50 |
+
self.remap = remap
|
51 |
+
if self.remap is not None:
|
52 |
+
self.register_buffer("used", torch.tensor(np.load(self.remap)))
|
53 |
+
self.re_embed = self.used.shape[0]
|
54 |
+
self.unknown_index = unknown_index # "random" or "extra" or integer
|
55 |
+
if self.unknown_index == "extra":
|
56 |
+
self.unknown_index = self.re_embed
|
57 |
+
self.re_embed = self.re_embed + 1
|
58 |
+
print(f"Remapping {self.n_e} indices to {self.re_embed} indices. "
|
59 |
+
f"Using {self.unknown_index} for unknown indices.")
|
60 |
+
else:
|
61 |
+
self.re_embed = n_e
|
62 |
+
|
63 |
+
self.sane_index_shape = sane_index_shape
|
64 |
+
|
65 |
+
def remap_to_used(self, inds):
|
66 |
+
ishape = inds.shape
|
67 |
+
assert len(ishape) > 1
|
68 |
+
inds = inds.reshape(ishape[0], -1)
|
69 |
+
used = self.used.to(inds)
|
70 |
+
match = (inds[:, :, None] == used[None, None, ...]).long()
|
71 |
+
new = match.argmax(-1)
|
72 |
+
unknown = match.sum(2) < 1
|
73 |
+
if self.unknown_index == "random":
|
74 |
+
new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)
|
75 |
+
else:
|
76 |
+
new[unknown] = self.unknown_index
|
77 |
+
return new.reshape(ishape)
|
78 |
+
|
79 |
+
def unmap_to_all(self, inds):
|
80 |
+
ishape = inds.shape
|
81 |
+
assert len(ishape) > 1
|
82 |
+
inds = inds.reshape(ishape[0], -1)
|
83 |
+
used = self.used.to(inds)
|
84 |
+
if self.re_embed > self.used.shape[0]: # extra token
|
85 |
+
inds[inds >= self.used.shape[0]] = 0 # simply set to zero
|
86 |
+
back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)
|
87 |
+
return back.reshape(ishape)
|
88 |
+
|
89 |
+
def forward(self, z, temp=None, rescale_logits=False, return_logits=False):
|
90 |
+
assert temp is None or temp == 1.0, "Only for interface compatible with Gumbel"
|
91 |
+
assert rescale_logits is False, "Only for interface compatible with Gumbel"
|
92 |
+
assert return_logits is False, "Only for interface compatible with Gumbel"
|
93 |
+
# reshape z -> (batch, height, width, channel) and flatten
|
94 |
+
z = rearrange(z, 'b c h w -> b h w c').contiguous()
|
95 |
+
z_flattened = z.view(-1, self.e_dim)
|
96 |
+
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
|
97 |
+
|
98 |
+
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
99 |
+
torch.sum(self.embedding.weight ** 2, dim=1) - 2 * \
|
100 |
+
torch.einsum('bd,dn->bn', z_flattened, rearrange(self.embedding.weight, 'n d -> d n'))
|
101 |
+
|
102 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
103 |
+
z_q = self.embedding(min_encoding_indices).view(z.shape)
|
104 |
+
perplexity = None
|
105 |
+
min_encodings = None
|
106 |
+
|
107 |
+
# compute loss for embedding
|
108 |
+
if not self.legacy:
|
109 |
+
loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + \
|
110 |
+
torch.mean((z_q - z.detach()) ** 2)
|
111 |
+
else:
|
112 |
+
loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * \
|
113 |
+
torch.mean((z_q - z.detach()) ** 2)
|
114 |
+
|
115 |
+
# preserve gradients
|
116 |
+
z_q = z + (z_q - z).detach()
|
117 |
+
|
118 |
+
# reshape back to match original input shape
|
119 |
+
z_q = rearrange(z_q, 'b h w c -> b c h w').contiguous()
|
120 |
+
|
121 |
+
if self.remap is not None:
|
122 |
+
min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis
|
123 |
+
min_encoding_indices = self.remap_to_used(min_encoding_indices)
|
124 |
+
min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten
|
125 |
+
|
126 |
+
if self.sane_index_shape:
|
127 |
+
min_encoding_indices = min_encoding_indices.reshape(
|
128 |
+
z_q.shape[0], z_q.shape[2], z_q.shape[3])
|
129 |
+
|
130 |
+
return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
|
131 |
+
|
132 |
+
def get_codebook_entry(self, indices, shape):
|
133 |
+
# shape specifying (batch, height, width, channel)
|
134 |
+
if self.remap is not None:
|
135 |
+
indices = indices.reshape(shape[0], -1) # add batch axis
|
136 |
+
indices = self.unmap_to_all(indices)
|
137 |
+
indices = indices.reshape(-1) # flatten again
|
138 |
+
|
139 |
+
# get quantized latent vectors
|
140 |
+
z_q = self.embedding(indices)
|
141 |
+
|
142 |
+
if shape is not None:
|
143 |
+
z_q = z_q.view(shape)
|
144 |
+
# reshape back to match original input shape
|
145 |
+
z_q = z_q.permute(0, 3, 1, 2).contiguous()
|
146 |
+
|
147 |
+
return z_q
|
extensions-builtin/Lora/extra_networks_lora.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from modules import extra_networks, shared
|
2 |
+
import networks
|
3 |
+
|
4 |
+
|
5 |
+
class ExtraNetworkLora(extra_networks.ExtraNetwork):
|
6 |
+
def __init__(self):
|
7 |
+
super().__init__('lora')
|
8 |
+
|
9 |
+
self.errors = {}
|
10 |
+
"""mapping of network names to the number of errors the network had during operation"""
|
11 |
+
|
12 |
+
remove_symbols = str.maketrans('', '', ":,")
|
13 |
+
|
14 |
+
def activate(self, p, params_list):
|
15 |
+
additional = shared.opts.sd_lora
|
16 |
+
|
17 |
+
self.errors.clear()
|
18 |
+
|
19 |
+
if additional != "None" and additional in networks.available_networks and not any(x for x in params_list if x.items[0] == additional):
|
20 |
+
p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" for x in p.all_prompts]
|
21 |
+
params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
|
22 |
+
|
23 |
+
names = []
|
24 |
+
te_multipliers = []
|
25 |
+
unet_multipliers = []
|
26 |
+
dyn_dims = []
|
27 |
+
for params in params_list:
|
28 |
+
assert params.items
|
29 |
+
|
30 |
+
names.append(params.positional[0])
|
31 |
+
|
32 |
+
te_multiplier = float(params.positional[1]) if len(params.positional) > 1 else 1.0
|
33 |
+
te_multiplier = float(params.named.get("te", te_multiplier))
|
34 |
+
|
35 |
+
unet_multiplier = float(params.positional[2]) if len(params.positional) > 2 else te_multiplier
|
36 |
+
unet_multiplier = float(params.named.get("unet", unet_multiplier))
|
37 |
+
|
38 |
+
dyn_dim = int(params.positional[3]) if len(params.positional) > 3 else None
|
39 |
+
dyn_dim = int(params.named["dyn"]) if "dyn" in params.named else dyn_dim
|
40 |
+
|
41 |
+
te_multipliers.append(te_multiplier)
|
42 |
+
unet_multipliers.append(unet_multiplier)
|
43 |
+
dyn_dims.append(dyn_dim)
|
44 |
+
|
45 |
+
networks.load_networks(names, te_multipliers, unet_multipliers, dyn_dims)
|
46 |
+
|
47 |
+
if shared.opts.lora_add_hashes_to_infotext:
|
48 |
+
if not getattr(p, "is_hr_pass", False) or not hasattr(p, "lora_hashes"):
|
49 |
+
p.lora_hashes = {}
|
50 |
+
|
51 |
+
for item in networks.loaded_networks:
|
52 |
+
if item.network_on_disk.shorthash and item.mentioned_name:
|
53 |
+
p.lora_hashes[item.mentioned_name.translate(self.remove_symbols)] = item.network_on_disk.shorthash
|
54 |
+
|
55 |
+
if p.lora_hashes:
|
56 |
+
p.extra_generation_params["Lora hashes"] = ', '.join(f'{k}: {v}' for k, v in p.lora_hashes.items())
|
57 |
+
|
58 |
+
def deactivate(self, p):
|
59 |
+
if self.errors:
|
60 |
+
p.comment("Networks with errors: " + ", ".join(f"{k} ({v})" for k, v in self.errors.items()))
|
61 |
+
|
62 |
+
self.errors.clear()
|
extensions-builtin/Lora/lora.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networks
|
2 |
+
|
3 |
+
list_available_loras = networks.list_available_networks
|
4 |
+
|
5 |
+
available_loras = networks.available_networks
|
6 |
+
available_lora_aliases = networks.available_network_aliases
|
7 |
+
available_lora_hash_lookup = networks.available_network_hash_lookup
|
8 |
+
forbidden_lora_aliases = networks.forbidden_network_aliases
|
9 |
+
loaded_loras = networks.loaded_networks
|
extensions-builtin/Lora/lora_logger.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import copy
|
3 |
+
import logging
|
4 |
+
|
5 |
+
|
6 |
+
class ColoredFormatter(logging.Formatter):
|
7 |
+
COLORS = {
|
8 |
+
"DEBUG": "\033[0;36m", # CYAN
|
9 |
+
"INFO": "\033[0;32m", # GREEN
|
10 |
+
"WARNING": "\033[0;33m", # YELLOW
|
11 |
+
"ERROR": "\033[0;31m", # RED
|
12 |
+
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
|
13 |
+
"RESET": "\033[0m", # RESET COLOR
|
14 |
+
}
|
15 |
+
|
16 |
+
def format(self, record):
|
17 |
+
colored_record = copy.copy(record)
|
18 |
+
levelname = colored_record.levelname
|
19 |
+
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
|
20 |
+
colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
|
21 |
+
return super().format(colored_record)
|
22 |
+
|
23 |
+
|
24 |
+
logger = logging.getLogger("lora")
|
25 |
+
logger.propagate = False
|
26 |
+
|
27 |
+
|
28 |
+
if not logger.handlers:
|
29 |
+
handler = logging.StreamHandler(sys.stdout)
|
30 |
+
handler.setFormatter(
|
31 |
+
ColoredFormatter("[%(name)s]-%(levelname)s: %(message)s")
|
32 |
+
)
|
33 |
+
logger.addHandler(handler)
|
extensions-builtin/Lora/lora_patches.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import networks
|
4 |
+
from modules import patches
|
5 |
+
|
6 |
+
|
7 |
+
class LoraPatches:
|
8 |
+
def __init__(self):
|
9 |
+
self.Linear_forward = patches.patch(__name__, torch.nn.Linear, 'forward', networks.network_Linear_forward)
|
10 |
+
self.Linear_load_state_dict = patches.patch(__name__, torch.nn.Linear, '_load_from_state_dict', networks.network_Linear_load_state_dict)
|
11 |
+
self.Conv2d_forward = patches.patch(__name__, torch.nn.Conv2d, 'forward', networks.network_Conv2d_forward)
|
12 |
+
self.Conv2d_load_state_dict = patches.patch(__name__, torch.nn.Conv2d, '_load_from_state_dict', networks.network_Conv2d_load_state_dict)
|
13 |
+
self.GroupNorm_forward = patches.patch(__name__, torch.nn.GroupNorm, 'forward', networks.network_GroupNorm_forward)
|
14 |
+
self.GroupNorm_load_state_dict = patches.patch(__name__, torch.nn.GroupNorm, '_load_from_state_dict', networks.network_GroupNorm_load_state_dict)
|
15 |
+
self.LayerNorm_forward = patches.patch(__name__, torch.nn.LayerNorm, 'forward', networks.network_LayerNorm_forward)
|
16 |
+
self.LayerNorm_load_state_dict = patches.patch(__name__, torch.nn.LayerNorm, '_load_from_state_dict', networks.network_LayerNorm_load_state_dict)
|
17 |
+
self.MultiheadAttention_forward = patches.patch(__name__, torch.nn.MultiheadAttention, 'forward', networks.network_MultiheadAttention_forward)
|
18 |
+
self.MultiheadAttention_load_state_dict = patches.patch(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict', networks.network_MultiheadAttention_load_state_dict)
|
19 |
+
|
20 |
+
def undo(self):
|
21 |
+
self.Linear_forward = patches.undo(__name__, torch.nn.Linear, 'forward')
|
22 |
+
self.Linear_load_state_dict = patches.undo(__name__, torch.nn.Linear, '_load_from_state_dict')
|
23 |
+
self.Conv2d_forward = patches.undo(__name__, torch.nn.Conv2d, 'forward')
|
24 |
+
self.Conv2d_load_state_dict = patches.undo(__name__, torch.nn.Conv2d, '_load_from_state_dict')
|
25 |
+
self.GroupNorm_forward = patches.undo(__name__, torch.nn.GroupNorm, 'forward')
|
26 |
+
self.GroupNorm_load_state_dict = patches.undo(__name__, torch.nn.GroupNorm, '_load_from_state_dict')
|
27 |
+
self.LayerNorm_forward = patches.undo(__name__, torch.nn.LayerNorm, 'forward')
|
28 |
+
self.LayerNorm_load_state_dict = patches.undo(__name__, torch.nn.LayerNorm, '_load_from_state_dict')
|
29 |
+
self.MultiheadAttention_forward = patches.undo(__name__, torch.nn.MultiheadAttention, 'forward')
|
30 |
+
self.MultiheadAttention_load_state_dict = patches.undo(__name__, torch.nn.MultiheadAttention, '_load_from_state_dict')
|
31 |
+
|
extensions-builtin/Lora/lyco_helpers.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
|
4 |
+
def make_weight_cp(t, wa, wb):
|
5 |
+
temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
|
6 |
+
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
|
7 |
+
|
8 |
+
|
9 |
+
def rebuild_conventional(up, down, shape, dyn_dim=None):
|
10 |
+
up = up.reshape(up.size(0), -1)
|
11 |
+
down = down.reshape(down.size(0), -1)
|
12 |
+
if dyn_dim is not None:
|
13 |
+
up = up[:, :dyn_dim]
|
14 |
+
down = down[:dyn_dim, :]
|
15 |
+
return (up @ down).reshape(shape)
|
16 |
+
|
17 |
+
|
18 |
+
def rebuild_cp_decomposition(up, down, mid):
|
19 |
+
up = up.reshape(up.size(0), -1)
|
20 |
+
down = down.reshape(down.size(0), -1)
|
21 |
+
return torch.einsum('n m k l, i n, m j -> i j k l', mid, up, down)
|
22 |
+
|
23 |
+
|
24 |
+
# copied from https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/lokr.py
|
25 |
+
def factorization(dimension: int, factor:int=-1) -> tuple[int, int]:
|
26 |
+
'''
|
27 |
+
return a tuple of two value of input dimension decomposed by the number closest to factor
|
28 |
+
second value is higher or equal than first value.
|
29 |
+
|
30 |
+
In LoRA with Kroneckor Product, first value is a value for weight scale.
|
31 |
+
secon value is a value for weight.
|
32 |
+
|
33 |
+
Because of non-commutative property, A⊗B ≠ B⊗A. Meaning of two matrices is slightly different.
|
34 |
+
|
35 |
+
examples)
|
36 |
+
factor
|
37 |
+
-1 2 4 8 16 ...
|
38 |
+
127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127
|
39 |
+
128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 16
|
40 |
+
250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 25
|
41 |
+
360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 30
|
42 |
+
512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32
|
43 |
+
1024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 64
|
44 |
+
'''
|
45 |
+
|
46 |
+
if factor > 0 and (dimension % factor) == 0:
|
47 |
+
m = factor
|
48 |
+
n = dimension // factor
|
49 |
+
if m > n:
|
50 |
+
n, m = m, n
|
51 |
+
return m, n
|
52 |
+
if factor < 0:
|
53 |
+
factor = dimension
|
54 |
+
m, n = 1, dimension
|
55 |
+
length = m + n
|
56 |
+
while m<n:
|
57 |
+
new_m = m + 1
|
58 |
+
while dimension%new_m != 0:
|
59 |
+
new_m += 1
|
60 |
+
new_n = dimension // new_m
|
61 |
+
if new_m + new_n > length or new_m>factor:
|
62 |
+
break
|
63 |
+
else:
|
64 |
+
m, n = new_m, new_n
|
65 |
+
if m > n:
|
66 |
+
n, m = m, n
|
67 |
+
return m, n
|
68 |
+
|
extensions-builtin/Lora/network.py
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
import os
|
3 |
+
from collections import namedtuple
|
4 |
+
import enum
|
5 |
+
|
6 |
+
import torch.nn as nn
|
7 |
+
import torch.nn.functional as F
|
8 |
+
|
9 |
+
from modules import sd_models, cache, errors, hashes, shared
|
10 |
+
import modules.models.sd3.mmdit
|
11 |
+
|
12 |
+
NetworkWeights = namedtuple('NetworkWeights', ['network_key', 'sd_key', 'w', 'sd_module'])
|
13 |
+
|
14 |
+
metadata_tags_order = {"ss_sd_model_name": 1, "ss_resolution": 2, "ss_clip_skip": 3, "ss_num_train_images": 10, "ss_tag_frequency": 20}
|
15 |
+
|
16 |
+
|
17 |
+
class SdVersion(enum.Enum):
|
18 |
+
Unknown = 1
|
19 |
+
SD1 = 2
|
20 |
+
SD2 = 3
|
21 |
+
SDXL = 4
|
22 |
+
|
23 |
+
|
24 |
+
class NetworkOnDisk:
|
25 |
+
def __init__(self, name, filename):
|
26 |
+
self.name = name
|
27 |
+
self.filename = filename
|
28 |
+
self.metadata = {}
|
29 |
+
self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors"
|
30 |
+
|
31 |
+
def read_metadata():
|
32 |
+
metadata = sd_models.read_metadata_from_safetensors(filename)
|
33 |
+
|
34 |
+
return metadata
|
35 |
+
|
36 |
+
if self.is_safetensors:
|
37 |
+
try:
|
38 |
+
self.metadata = cache.cached_data_for_file('safetensors-metadata', "lora/" + self.name, filename, read_metadata)
|
39 |
+
except Exception as e:
|
40 |
+
errors.display(e, f"reading lora {filename}")
|
41 |
+
|
42 |
+
if self.metadata:
|
43 |
+
m = {}
|
44 |
+
for k, v in sorted(self.metadata.items(), key=lambda x: metadata_tags_order.get(x[0], 999)):
|
45 |
+
m[k] = v
|
46 |
+
|
47 |
+
self.metadata = m
|
48 |
+
|
49 |
+
self.alias = self.metadata.get('ss_output_name', self.name)
|
50 |
+
|
51 |
+
self.hash = None
|
52 |
+
self.shorthash = None
|
53 |
+
self.set_hash(
|
54 |
+
self.metadata.get('sshs_model_hash') or
|
55 |
+
hashes.sha256_from_cache(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or
|
56 |
+
''
|
57 |
+
)
|
58 |
+
|
59 |
+
self.sd_version = self.detect_version()
|
60 |
+
|
61 |
+
def detect_version(self):
|
62 |
+
if str(self.metadata.get('ss_base_model_version', "")).startswith("sdxl_"):
|
63 |
+
return SdVersion.SDXL
|
64 |
+
elif str(self.metadata.get('ss_v2', "")) == "True":
|
65 |
+
return SdVersion.SD2
|
66 |
+
elif len(self.metadata):
|
67 |
+
return SdVersion.SD1
|
68 |
+
|
69 |
+
return SdVersion.Unknown
|
70 |
+
|
71 |
+
def set_hash(self, v):
|
72 |
+
self.hash = v
|
73 |
+
self.shorthash = self.hash[0:12]
|
74 |
+
|
75 |
+
if self.shorthash:
|
76 |
+
import networks
|
77 |
+
networks.available_network_hash_lookup[self.shorthash] = self
|
78 |
+
|
79 |
+
def read_hash(self):
|
80 |
+
if not self.hash:
|
81 |
+
self.set_hash(hashes.sha256(self.filename, "lora/" + self.name, use_addnet_hash=self.is_safetensors) or '')
|
82 |
+
|
83 |
+
def get_alias(self):
|
84 |
+
import networks
|
85 |
+
if shared.opts.lora_preferred_name == "Filename" or self.alias.lower() in networks.forbidden_network_aliases:
|
86 |
+
return self.name
|
87 |
+
else:
|
88 |
+
return self.alias
|
89 |
+
|
90 |
+
|
91 |
+
class Network: # LoraModule
|
92 |
+
def __init__(self, name, network_on_disk: NetworkOnDisk):
|
93 |
+
self.name = name
|
94 |
+
self.network_on_disk = network_on_disk
|
95 |
+
self.te_multiplier = 1.0
|
96 |
+
self.unet_multiplier = 1.0
|
97 |
+
self.dyn_dim = None
|
98 |
+
self.modules = {}
|
99 |
+
self.bundle_embeddings = {}
|
100 |
+
self.mtime = None
|
101 |
+
|
102 |
+
self.mentioned_name = None
|
103 |
+
"""the text that was used to add the network to prompt - can be either name or an alias"""
|
104 |
+
|
105 |
+
|
106 |
+
class ModuleType:
|
107 |
+
def create_module(self, net: Network, weights: NetworkWeights) -> Network | None:
|
108 |
+
return None
|
109 |
+
|
110 |
+
|
111 |
+
class NetworkModule:
|
112 |
+
def __init__(self, net: Network, weights: NetworkWeights):
|
113 |
+
self.network = net
|
114 |
+
self.network_key = weights.network_key
|
115 |
+
self.sd_key = weights.sd_key
|
116 |
+
self.sd_module = weights.sd_module
|
117 |
+
|
118 |
+
if isinstance(self.sd_module, modules.models.sd3.mmdit.QkvLinear):
|
119 |
+
s = self.sd_module.weight.shape
|
120 |
+
self.shape = (s[0] // 3, s[1])
|
121 |
+
elif hasattr(self.sd_module, 'weight'):
|
122 |
+
self.shape = self.sd_module.weight.shape
|
123 |
+
elif isinstance(self.sd_module, nn.MultiheadAttention):
|
124 |
+
# For now, only self-attn use Pytorch's MHA
|
125 |
+
# So assume all qkvo proj have same shape
|
126 |
+
self.shape = self.sd_module.out_proj.weight.shape
|
127 |
+
else:
|
128 |
+
self.shape = None
|
129 |
+
|
130 |
+
self.ops = None
|
131 |
+
self.extra_kwargs = {}
|
132 |
+
if isinstance(self.sd_module, nn.Conv2d):
|
133 |
+
self.ops = F.conv2d
|
134 |
+
self.extra_kwargs = {
|
135 |
+
'stride': self.sd_module.stride,
|
136 |
+
'padding': self.sd_module.padding
|
137 |
+
}
|
138 |
+
elif isinstance(self.sd_module, nn.Linear):
|
139 |
+
self.ops = F.linear
|
140 |
+
elif isinstance(self.sd_module, nn.LayerNorm):
|
141 |
+
self.ops = F.layer_norm
|
142 |
+
self.extra_kwargs = {
|
143 |
+
'normalized_shape': self.sd_module.normalized_shape,
|
144 |
+
'eps': self.sd_module.eps
|
145 |
+
}
|
146 |
+
elif isinstance(self.sd_module, nn.GroupNorm):
|
147 |
+
self.ops = F.group_norm
|
148 |
+
self.extra_kwargs = {
|
149 |
+
'num_groups': self.sd_module.num_groups,
|
150 |
+
'eps': self.sd_module.eps
|
151 |
+
}
|
152 |
+
|
153 |
+
self.dim = None
|
154 |
+
self.bias = weights.w.get("bias")
|
155 |
+
self.alpha = weights.w["alpha"].item() if "alpha" in weights.w else None
|
156 |
+
self.scale = weights.w["scale"].item() if "scale" in weights.w else None
|
157 |
+
|
158 |
+
self.dora_scale = weights.w.get("dora_scale", None)
|
159 |
+
self.dora_norm_dims = len(self.shape) - 1
|
160 |
+
|
161 |
+
def multiplier(self):
|
162 |
+
if 'transformer' in self.sd_key[:20]:
|
163 |
+
return self.network.te_multiplier
|
164 |
+
else:
|
165 |
+
return self.network.unet_multiplier
|
166 |
+
|
167 |
+
def calc_scale(self):
|
168 |
+
if self.scale is not None:
|
169 |
+
return self.scale
|
170 |
+
if self.dim is not None and self.alpha is not None:
|
171 |
+
return self.alpha / self.dim
|
172 |
+
|
173 |
+
return 1.0
|
174 |
+
|
175 |
+
def apply_weight_decompose(self, updown, orig_weight):
|
176 |
+
# Match the device/dtype
|
177 |
+
orig_weight = orig_weight.to(updown.dtype)
|
178 |
+
dora_scale = self.dora_scale.to(device=orig_weight.device, dtype=updown.dtype)
|
179 |
+
updown = updown.to(orig_weight.device)
|
180 |
+
|
181 |
+
merged_scale1 = updown + orig_weight
|
182 |
+
merged_scale1_norm = (
|
183 |
+
merged_scale1.transpose(0, 1)
|
184 |
+
.reshape(merged_scale1.shape[1], -1)
|
185 |
+
.norm(dim=1, keepdim=True)
|
186 |
+
.reshape(merged_scale1.shape[1], *[1] * self.dora_norm_dims)
|
187 |
+
.transpose(0, 1)
|
188 |
+
)
|
189 |
+
|
190 |
+
dora_merged = (
|
191 |
+
merged_scale1 * (dora_scale / merged_scale1_norm)
|
192 |
+
)
|
193 |
+
final_updown = dora_merged - orig_weight
|
194 |
+
return final_updown
|
195 |
+
|
196 |
+
def finalize_updown(self, updown, orig_weight, output_shape, ex_bias=None):
|
197 |
+
if self.bias is not None:
|
198 |
+
updown = updown.reshape(self.bias.shape)
|
199 |
+
updown += self.bias.to(orig_weight.device, dtype=updown.dtype)
|
200 |
+
updown = updown.reshape(output_shape)
|
201 |
+
|
202 |
+
if len(output_shape) == 4:
|
203 |
+
updown = updown.reshape(output_shape)
|
204 |
+
|
205 |
+
if orig_weight.size().numel() == updown.size().numel():
|
206 |
+
updown = updown.reshape(orig_weight.shape)
|
207 |
+
|
208 |
+
if ex_bias is not None:
|
209 |
+
ex_bias = ex_bias * self.multiplier()
|
210 |
+
|
211 |
+
updown = updown * self.calc_scale()
|
212 |
+
|
213 |
+
if self.dora_scale is not None:
|
214 |
+
updown = self.apply_weight_decompose(updown, orig_weight)
|
215 |
+
|
216 |
+
return updown * self.multiplier(), ex_bias
|
217 |
+
|
218 |
+
def calc_updown(self, target):
|
219 |
+
raise NotImplementedError()
|
220 |
+
|
221 |
+
def forward(self, x, y):
|
222 |
+
"""A general forward implementation for all modules"""
|
223 |
+
if self.ops is None:
|
224 |
+
raise NotImplementedError()
|
225 |
+
else:
|
226 |
+
updown, ex_bias = self.calc_updown(self.sd_module.weight)
|
227 |
+
return y + self.ops(x, weight=updown, bias=ex_bias, **self.extra_kwargs)
|
228 |
+
|
extensions-builtin/Lora/network_full.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import network
|
2 |
+
|
3 |
+
|
4 |
+
class ModuleTypeFull(network.ModuleType):
|
5 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
6 |
+
if all(x in weights.w for x in ["diff"]):
|
7 |
+
return NetworkModuleFull(net, weights)
|
8 |
+
|
9 |
+
return None
|
10 |
+
|
11 |
+
|
12 |
+
class NetworkModuleFull(network.NetworkModule):
|
13 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
14 |
+
super().__init__(net, weights)
|
15 |
+
|
16 |
+
self.weight = weights.w.get("diff")
|
17 |
+
self.ex_bias = weights.w.get("diff_b")
|
18 |
+
|
19 |
+
def calc_updown(self, orig_weight):
|
20 |
+
output_shape = self.weight.shape
|
21 |
+
updown = self.weight.to(orig_weight.device)
|
22 |
+
if self.ex_bias is not None:
|
23 |
+
ex_bias = self.ex_bias.to(orig_weight.device)
|
24 |
+
else:
|
25 |
+
ex_bias = None
|
26 |
+
|
27 |
+
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
extensions-builtin/Lora/network_glora.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import network
|
3 |
+
|
4 |
+
class ModuleTypeGLora(network.ModuleType):
|
5 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
6 |
+
if all(x in weights.w for x in ["a1.weight", "a2.weight", "alpha", "b1.weight", "b2.weight"]):
|
7 |
+
return NetworkModuleGLora(net, weights)
|
8 |
+
|
9 |
+
return None
|
10 |
+
|
11 |
+
# adapted from https://github.com/KohakuBlueleaf/LyCORIS
|
12 |
+
class NetworkModuleGLora(network.NetworkModule):
|
13 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
14 |
+
super().__init__(net, weights)
|
15 |
+
|
16 |
+
if hasattr(self.sd_module, 'weight'):
|
17 |
+
self.shape = self.sd_module.weight.shape
|
18 |
+
|
19 |
+
self.w1a = weights.w["a1.weight"]
|
20 |
+
self.w1b = weights.w["b1.weight"]
|
21 |
+
self.w2a = weights.w["a2.weight"]
|
22 |
+
self.w2b = weights.w["b2.weight"]
|
23 |
+
|
24 |
+
def calc_updown(self, orig_weight):
|
25 |
+
w1a = self.w1a.to(orig_weight.device)
|
26 |
+
w1b = self.w1b.to(orig_weight.device)
|
27 |
+
w2a = self.w2a.to(orig_weight.device)
|
28 |
+
w2b = self.w2b.to(orig_weight.device)
|
29 |
+
|
30 |
+
output_shape = [w1a.size(0), w1b.size(1)]
|
31 |
+
updown = ((w2b @ w1b) + ((orig_weight.to(dtype = w1a.dtype) @ w2a) @ w1a))
|
32 |
+
|
33 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
extensions-builtin/Lora/network_hada.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import lyco_helpers
|
2 |
+
import network
|
3 |
+
|
4 |
+
|
5 |
+
class ModuleTypeHada(network.ModuleType):
|
6 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
7 |
+
if all(x in weights.w for x in ["hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b"]):
|
8 |
+
return NetworkModuleHada(net, weights)
|
9 |
+
|
10 |
+
return None
|
11 |
+
|
12 |
+
|
13 |
+
class NetworkModuleHada(network.NetworkModule):
|
14 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
15 |
+
super().__init__(net, weights)
|
16 |
+
|
17 |
+
if hasattr(self.sd_module, 'weight'):
|
18 |
+
self.shape = self.sd_module.weight.shape
|
19 |
+
|
20 |
+
self.w1a = weights.w["hada_w1_a"]
|
21 |
+
self.w1b = weights.w["hada_w1_b"]
|
22 |
+
self.dim = self.w1b.shape[0]
|
23 |
+
self.w2a = weights.w["hada_w2_a"]
|
24 |
+
self.w2b = weights.w["hada_w2_b"]
|
25 |
+
|
26 |
+
self.t1 = weights.w.get("hada_t1")
|
27 |
+
self.t2 = weights.w.get("hada_t2")
|
28 |
+
|
29 |
+
def calc_updown(self, orig_weight):
|
30 |
+
w1a = self.w1a.to(orig_weight.device)
|
31 |
+
w1b = self.w1b.to(orig_weight.device)
|
32 |
+
w2a = self.w2a.to(orig_weight.device)
|
33 |
+
w2b = self.w2b.to(orig_weight.device)
|
34 |
+
|
35 |
+
output_shape = [w1a.size(0), w1b.size(1)]
|
36 |
+
|
37 |
+
if self.t1 is not None:
|
38 |
+
output_shape = [w1a.size(1), w1b.size(1)]
|
39 |
+
t1 = self.t1.to(orig_weight.device)
|
40 |
+
updown1 = lyco_helpers.make_weight_cp(t1, w1a, w1b)
|
41 |
+
output_shape += t1.shape[2:]
|
42 |
+
else:
|
43 |
+
if len(w1b.shape) == 4:
|
44 |
+
output_shape += w1b.shape[2:]
|
45 |
+
updown1 = lyco_helpers.rebuild_conventional(w1a, w1b, output_shape)
|
46 |
+
|
47 |
+
if self.t2 is not None:
|
48 |
+
t2 = self.t2.to(orig_weight.device)
|
49 |
+
updown2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
50 |
+
else:
|
51 |
+
updown2 = lyco_helpers.rebuild_conventional(w2a, w2b, output_shape)
|
52 |
+
|
53 |
+
updown = updown1 * updown2
|
54 |
+
|
55 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
extensions-builtin/Lora/network_ia3.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import network
|
2 |
+
|
3 |
+
|
4 |
+
class ModuleTypeIa3(network.ModuleType):
|
5 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
6 |
+
if all(x in weights.w for x in ["weight"]):
|
7 |
+
return NetworkModuleIa3(net, weights)
|
8 |
+
|
9 |
+
return None
|
10 |
+
|
11 |
+
|
12 |
+
class NetworkModuleIa3(network.NetworkModule):
|
13 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
14 |
+
super().__init__(net, weights)
|
15 |
+
|
16 |
+
self.w = weights.w["weight"]
|
17 |
+
self.on_input = weights.w["on_input"].item()
|
18 |
+
|
19 |
+
def calc_updown(self, orig_weight):
|
20 |
+
w = self.w.to(orig_weight.device)
|
21 |
+
|
22 |
+
output_shape = [w.size(0), orig_weight.size(1)]
|
23 |
+
if self.on_input:
|
24 |
+
output_shape.reverse()
|
25 |
+
else:
|
26 |
+
w = w.reshape(-1, 1)
|
27 |
+
|
28 |
+
updown = orig_weight * w
|
29 |
+
|
30 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
extensions-builtin/Lora/network_lokr.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import lyco_helpers
|
4 |
+
import network
|
5 |
+
|
6 |
+
|
7 |
+
class ModuleTypeLokr(network.ModuleType):
|
8 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
9 |
+
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
|
10 |
+
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
|
11 |
+
if has_1 and has_2:
|
12 |
+
return NetworkModuleLokr(net, weights)
|
13 |
+
|
14 |
+
return None
|
15 |
+
|
16 |
+
|
17 |
+
def make_kron(orig_shape, w1, w2):
|
18 |
+
if len(w2.shape) == 4:
|
19 |
+
w1 = w1.unsqueeze(2).unsqueeze(2)
|
20 |
+
w2 = w2.contiguous()
|
21 |
+
return torch.kron(w1, w2).reshape(orig_shape)
|
22 |
+
|
23 |
+
|
24 |
+
class NetworkModuleLokr(network.NetworkModule):
|
25 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
26 |
+
super().__init__(net, weights)
|
27 |
+
|
28 |
+
self.w1 = weights.w.get("lokr_w1")
|
29 |
+
self.w1a = weights.w.get("lokr_w1_a")
|
30 |
+
self.w1b = weights.w.get("lokr_w1_b")
|
31 |
+
self.dim = self.w1b.shape[0] if self.w1b is not None else self.dim
|
32 |
+
self.w2 = weights.w.get("lokr_w2")
|
33 |
+
self.w2a = weights.w.get("lokr_w2_a")
|
34 |
+
self.w2b = weights.w.get("lokr_w2_b")
|
35 |
+
self.dim = self.w2b.shape[0] if self.w2b is not None else self.dim
|
36 |
+
self.t2 = weights.w.get("lokr_t2")
|
37 |
+
|
38 |
+
def calc_updown(self, orig_weight):
|
39 |
+
if self.w1 is not None:
|
40 |
+
w1 = self.w1.to(orig_weight.device)
|
41 |
+
else:
|
42 |
+
w1a = self.w1a.to(orig_weight.device)
|
43 |
+
w1b = self.w1b.to(orig_weight.device)
|
44 |
+
w1 = w1a @ w1b
|
45 |
+
|
46 |
+
if self.w2 is not None:
|
47 |
+
w2 = self.w2.to(orig_weight.device)
|
48 |
+
elif self.t2 is None:
|
49 |
+
w2a = self.w2a.to(orig_weight.device)
|
50 |
+
w2b = self.w2b.to(orig_weight.device)
|
51 |
+
w2 = w2a @ w2b
|
52 |
+
else:
|
53 |
+
t2 = self.t2.to(orig_weight.device)
|
54 |
+
w2a = self.w2a.to(orig_weight.device)
|
55 |
+
w2b = self.w2b.to(orig_weight.device)
|
56 |
+
w2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
|
57 |
+
|
58 |
+
output_shape = [w1.size(0) * w2.size(0), w1.size(1) * w2.size(1)]
|
59 |
+
if len(orig_weight.shape) == 4:
|
60 |
+
output_shape = orig_weight.shape
|
61 |
+
|
62 |
+
updown = make_kron(output_shape, w1, w2)
|
63 |
+
|
64 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
extensions-builtin/Lora/network_lora.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import lyco_helpers
|
4 |
+
import modules.models.sd3.mmdit
|
5 |
+
import network
|
6 |
+
from modules import devices
|
7 |
+
|
8 |
+
|
9 |
+
class ModuleTypeLora(network.ModuleType):
|
10 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
11 |
+
if all(x in weights.w for x in ["lora_up.weight", "lora_down.weight"]):
|
12 |
+
return NetworkModuleLora(net, weights)
|
13 |
+
|
14 |
+
if all(x in weights.w for x in ["lora_A.weight", "lora_B.weight"]):
|
15 |
+
w = weights.w.copy()
|
16 |
+
weights.w.clear()
|
17 |
+
weights.w.update({"lora_up.weight": w["lora_B.weight"], "lora_down.weight": w["lora_A.weight"]})
|
18 |
+
|
19 |
+
return NetworkModuleLora(net, weights)
|
20 |
+
|
21 |
+
return None
|
22 |
+
|
23 |
+
|
24 |
+
class NetworkModuleLora(network.NetworkModule):
|
25 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
26 |
+
super().__init__(net, weights)
|
27 |
+
|
28 |
+
self.up_model = self.create_module(weights.w, "lora_up.weight")
|
29 |
+
self.down_model = self.create_module(weights.w, "lora_down.weight")
|
30 |
+
self.mid_model = self.create_module(weights.w, "lora_mid.weight", none_ok=True)
|
31 |
+
|
32 |
+
self.dim = weights.w["lora_down.weight"].shape[0]
|
33 |
+
|
34 |
+
def create_module(self, weights, key, none_ok=False):
|
35 |
+
weight = weights.get(key)
|
36 |
+
|
37 |
+
if weight is None and none_ok:
|
38 |
+
return None
|
39 |
+
|
40 |
+
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention, modules.models.sd3.mmdit.QkvLinear]
|
41 |
+
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
42 |
+
|
43 |
+
if is_linear:
|
44 |
+
weight = weight.reshape(weight.shape[0], -1)
|
45 |
+
module = torch.nn.Linear(weight.shape[1], weight.shape[0], bias=False)
|
46 |
+
elif is_conv and key == "lora_down.weight" or key == "dyn_up":
|
47 |
+
if len(weight.shape) == 2:
|
48 |
+
weight = weight.reshape(weight.shape[0], -1, 1, 1)
|
49 |
+
|
50 |
+
if weight.shape[2] != 1 or weight.shape[3] != 1:
|
51 |
+
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
52 |
+
else:
|
53 |
+
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
54 |
+
elif is_conv and key == "lora_mid.weight":
|
55 |
+
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], self.sd_module.kernel_size, self.sd_module.stride, self.sd_module.padding, bias=False)
|
56 |
+
elif is_conv and key == "lora_up.weight" or key == "dyn_down":
|
57 |
+
module = torch.nn.Conv2d(weight.shape[1], weight.shape[0], (1, 1), bias=False)
|
58 |
+
else:
|
59 |
+
raise AssertionError(f'Lora layer {self.network_key} matched a layer with unsupported type: {type(self.sd_module).__name__}')
|
60 |
+
|
61 |
+
with torch.no_grad():
|
62 |
+
if weight.shape != module.weight.shape:
|
63 |
+
weight = weight.reshape(module.weight.shape)
|
64 |
+
module.weight.copy_(weight)
|
65 |
+
|
66 |
+
module.to(device=devices.cpu, dtype=devices.dtype)
|
67 |
+
module.weight.requires_grad_(False)
|
68 |
+
|
69 |
+
return module
|
70 |
+
|
71 |
+
def calc_updown(self, orig_weight):
|
72 |
+
up = self.up_model.weight.to(orig_weight.device)
|
73 |
+
down = self.down_model.weight.to(orig_weight.device)
|
74 |
+
|
75 |
+
output_shape = [up.size(0), down.size(1)]
|
76 |
+
if self.mid_model is not None:
|
77 |
+
# cp-decomposition
|
78 |
+
mid = self.mid_model.weight.to(orig_weight.device)
|
79 |
+
updown = lyco_helpers.rebuild_cp_decomposition(up, down, mid)
|
80 |
+
output_shape += mid.shape[2:]
|
81 |
+
else:
|
82 |
+
if len(down.shape) == 4:
|
83 |
+
output_shape += down.shape[2:]
|
84 |
+
updown = lyco_helpers.rebuild_conventional(up, down, output_shape, self.network.dyn_dim)
|
85 |
+
|
86 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
87 |
+
|
88 |
+
def forward(self, x, y):
|
89 |
+
self.up_model.to(device=devices.device)
|
90 |
+
self.down_model.to(device=devices.device)
|
91 |
+
|
92 |
+
return y + self.up_model(self.down_model(x)) * self.multiplier() * self.calc_scale()
|
93 |
+
|
94 |
+
|
extensions-builtin/Lora/network_norm.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import network
|
2 |
+
|
3 |
+
|
4 |
+
class ModuleTypeNorm(network.ModuleType):
|
5 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
6 |
+
if all(x in weights.w for x in ["w_norm", "b_norm"]):
|
7 |
+
return NetworkModuleNorm(net, weights)
|
8 |
+
|
9 |
+
return None
|
10 |
+
|
11 |
+
|
12 |
+
class NetworkModuleNorm(network.NetworkModule):
|
13 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
14 |
+
super().__init__(net, weights)
|
15 |
+
|
16 |
+
self.w_norm = weights.w.get("w_norm")
|
17 |
+
self.b_norm = weights.w.get("b_norm")
|
18 |
+
|
19 |
+
def calc_updown(self, orig_weight):
|
20 |
+
output_shape = self.w_norm.shape
|
21 |
+
updown = self.w_norm.to(orig_weight.device)
|
22 |
+
|
23 |
+
if self.b_norm is not None:
|
24 |
+
ex_bias = self.b_norm.to(orig_weight.device)
|
25 |
+
else:
|
26 |
+
ex_bias = None
|
27 |
+
|
28 |
+
return self.finalize_updown(updown, orig_weight, output_shape, ex_bias)
|
extensions-builtin/Lora/network_oft.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import network
|
3 |
+
from einops import rearrange
|
4 |
+
|
5 |
+
|
6 |
+
class ModuleTypeOFT(network.ModuleType):
|
7 |
+
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
8 |
+
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
|
9 |
+
return NetworkModuleOFT(net, weights)
|
10 |
+
|
11 |
+
return None
|
12 |
+
|
13 |
+
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
|
14 |
+
# and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
|
15 |
+
class NetworkModuleOFT(network.NetworkModule):
|
16 |
+
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
17 |
+
|
18 |
+
super().__init__(net, weights)
|
19 |
+
|
20 |
+
self.lin_module = None
|
21 |
+
self.org_module: list[torch.Module] = [self.sd_module]
|
22 |
+
|
23 |
+
self.scale = 1.0
|
24 |
+
self.is_R = False
|
25 |
+
self.is_boft = False
|
26 |
+
|
27 |
+
# kohya-ss/New LyCORIS OFT/BOFT
|
28 |
+
if "oft_blocks" in weights.w.keys():
|
29 |
+
self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
|
30 |
+
self.alpha = weights.w.get("alpha", None) # alpha is constraint
|
31 |
+
self.dim = self.oft_blocks.shape[0] # lora dim
|
32 |
+
# Old LyCORIS OFT
|
33 |
+
elif "oft_diag" in weights.w.keys():
|
34 |
+
self.is_R = True
|
35 |
+
self.oft_blocks = weights.w["oft_diag"]
|
36 |
+
# self.alpha is unused
|
37 |
+
self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
|
38 |
+
|
39 |
+
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]
|
40 |
+
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
41 |
+
is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
|
42 |
+
|
43 |
+
if is_linear:
|
44 |
+
self.out_dim = self.sd_module.out_features
|
45 |
+
elif is_conv:
|
46 |
+
self.out_dim = self.sd_module.out_channels
|
47 |
+
elif is_other_linear:
|
48 |
+
self.out_dim = self.sd_module.embed_dim
|
49 |
+
|
50 |
+
# LyCORIS BOFT
|
51 |
+
if self.oft_blocks.dim() == 4:
|
52 |
+
self.is_boft = True
|
53 |
+
self.rescale = weights.w.get('rescale', None)
|
54 |
+
if self.rescale is not None and not is_other_linear:
|
55 |
+
self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1))
|
56 |
+
|
57 |
+
self.num_blocks = self.dim
|
58 |
+
self.block_size = self.out_dim // self.dim
|
59 |
+
self.constraint = (0 if self.alpha is None else self.alpha) * self.out_dim
|
60 |
+
if self.is_R:
|
61 |
+
self.constraint = None
|
62 |
+
self.block_size = self.dim
|
63 |
+
self.num_blocks = self.out_dim // self.dim
|
64 |
+
elif self.is_boft:
|
65 |
+
self.boft_m = self.oft_blocks.shape[0]
|
66 |
+
self.num_blocks = self.oft_blocks.shape[1]
|
67 |
+
self.block_size = self.oft_blocks.shape[2]
|
68 |
+
self.boft_b = self.block_size
|
69 |
+
|
70 |
+
def calc_updown(self, orig_weight):
|
71 |
+
oft_blocks = self.oft_blocks.to(orig_weight.device)
|
72 |
+
eye = torch.eye(self.block_size, device=oft_blocks.device)
|
73 |
+
|
74 |
+
if not self.is_R:
|
75 |
+
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
|
76 |
+
if self.constraint != 0:
|
77 |
+
norm_Q = torch.norm(block_Q.flatten())
|
78 |
+
new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
|
79 |
+
block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
|
80 |
+
oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
|
81 |
+
|
82 |
+
R = oft_blocks.to(orig_weight.device)
|
83 |
+
|
84 |
+
if not self.is_boft:
|
85 |
+
# This errors out for MultiheadAttention, might need to be handled up-stream
|
86 |
+
merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
|
87 |
+
merged_weight = torch.einsum(
|
88 |
+
'k n m, k n ... -> k m ...',
|
89 |
+
R,
|
90 |
+
merged_weight
|
91 |
+
)
|
92 |
+
merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
|
93 |
+
else:
|
94 |
+
# TODO: determine correct value for scale
|
95 |
+
scale = 1.0
|
96 |
+
m = self.boft_m
|
97 |
+
b = self.boft_b
|
98 |
+
r_b = b // 2
|
99 |
+
inp = orig_weight
|
100 |
+
for i in range(m):
|
101 |
+
bi = R[i] # b_num, b_size, b_size
|
102 |
+
if i == 0:
|
103 |
+
# Apply multiplier/scale and rescale into first weight
|
104 |
+
bi = bi * scale + (1 - scale) * eye
|
105 |
+
inp = rearrange(inp, "(c g k) ... -> (c k g) ...", g=2, k=2**i * r_b)
|
106 |
+
inp = rearrange(inp, "(d b) ... -> d b ...", b=b)
|
107 |
+
inp = torch.einsum("b i j, b j ... -> b i ...", bi, inp)
|
108 |
+
inp = rearrange(inp, "d b ... -> (d b) ...")
|
109 |
+
inp = rearrange(inp, "(c k g) ... -> (c g k) ...", g=2, k=2**i * r_b)
|
110 |
+
merged_weight = inp
|
111 |
+
|
112 |
+
# Rescale mechanism
|
113 |
+
if self.rescale is not None:
|
114 |
+
merged_weight = self.rescale.to(merged_weight) * merged_weight
|
115 |
+
|
116 |
+
updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
|
117 |
+
output_shape = orig_weight.shape
|
118 |
+
return self.finalize_updown(updown, orig_weight, output_shape)
|
extensions-builtin/Lora/networks.py
ADDED
@@ -0,0 +1,737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
import gradio as gr
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
|
7 |
+
import lora_patches
|
8 |
+
import network
|
9 |
+
import network_lora
|
10 |
+
import network_glora
|
11 |
+
import network_hada
|
12 |
+
import network_ia3
|
13 |
+
import network_lokr
|
14 |
+
import network_full
|
15 |
+
import network_norm
|
16 |
+
import network_oft
|
17 |
+
|
18 |
+
import torch
|
19 |
+
from typing import Union
|
20 |
+
|
21 |
+
from modules import shared, devices, sd_models, errors, scripts, sd_hijack
|
22 |
+
import modules.textual_inversion.textual_inversion as textual_inversion
|
23 |
+
import modules.models.sd3.mmdit
|
24 |
+
|
25 |
+
from lora_logger import logger
|
26 |
+
|
27 |
+
module_types = [
|
28 |
+
network_lora.ModuleTypeLora(),
|
29 |
+
network_hada.ModuleTypeHada(),
|
30 |
+
network_ia3.ModuleTypeIa3(),
|
31 |
+
network_lokr.ModuleTypeLokr(),
|
32 |
+
network_full.ModuleTypeFull(),
|
33 |
+
network_norm.ModuleTypeNorm(),
|
34 |
+
network_glora.ModuleTypeGLora(),
|
35 |
+
network_oft.ModuleTypeOFT(),
|
36 |
+
]
|
37 |
+
|
38 |
+
|
39 |
+
re_digits = re.compile(r"\d+")
|
40 |
+
re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
|
41 |
+
re_compiled = {}
|
42 |
+
|
43 |
+
suffix_conversion = {
|
44 |
+
"attentions": {},
|
45 |
+
"resnets": {
|
46 |
+
"conv1": "in_layers_2",
|
47 |
+
"conv2": "out_layers_3",
|
48 |
+
"norm1": "in_layers_0",
|
49 |
+
"norm2": "out_layers_0",
|
50 |
+
"time_emb_proj": "emb_layers_1",
|
51 |
+
"conv_shortcut": "skip_connection",
|
52 |
+
}
|
53 |
+
}
|
54 |
+
|
55 |
+
|
56 |
+
def convert_diffusers_name_to_compvis(key, is_sd2):
|
57 |
+
def match(match_list, regex_text):
|
58 |
+
regex = re_compiled.get(regex_text)
|
59 |
+
if regex is None:
|
60 |
+
regex = re.compile(regex_text)
|
61 |
+
re_compiled[regex_text] = regex
|
62 |
+
|
63 |
+
r = re.match(regex, key)
|
64 |
+
if not r:
|
65 |
+
return False
|
66 |
+
|
67 |
+
match_list.clear()
|
68 |
+
match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
|
69 |
+
return True
|
70 |
+
|
71 |
+
m = []
|
72 |
+
|
73 |
+
if match(m, r"lora_unet_conv_in(.*)"):
|
74 |
+
return f'diffusion_model_input_blocks_0_0{m[0]}'
|
75 |
+
|
76 |
+
if match(m, r"lora_unet_conv_out(.*)"):
|
77 |
+
return f'diffusion_model_out_2{m[0]}'
|
78 |
+
|
79 |
+
if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
|
80 |
+
return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
|
81 |
+
|
82 |
+
if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
83 |
+
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
84 |
+
return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
85 |
+
|
86 |
+
if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
|
87 |
+
suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
|
88 |
+
return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
|
89 |
+
|
90 |
+
if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
|
91 |
+
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
|
92 |
+
return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
|
93 |
+
|
94 |
+
if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
|
95 |
+
return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
|
96 |
+
|
97 |
+
if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
|
98 |
+
return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
|
99 |
+
|
100 |
+
if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
|
101 |
+
if is_sd2:
|
102 |
+
if 'mlp_fc1' in m[1]:
|
103 |
+
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
104 |
+
elif 'mlp_fc2' in m[1]:
|
105 |
+
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
106 |
+
else:
|
107 |
+
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
108 |
+
|
109 |
+
return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
|
110 |
+
|
111 |
+
if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
|
112 |
+
if 'mlp_fc1' in m[1]:
|
113 |
+
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
|
114 |
+
elif 'mlp_fc2' in m[1]:
|
115 |
+
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
|
116 |
+
else:
|
117 |
+
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
|
118 |
+
|
119 |
+
return key
|
120 |
+
|
121 |
+
|
122 |
+
def assign_network_names_to_compvis_modules(sd_model):
|
123 |
+
network_layer_mapping = {}
|
124 |
+
|
125 |
+
if shared.sd_model.is_sdxl:
|
126 |
+
for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
|
127 |
+
if not hasattr(embedder, 'wrapped'):
|
128 |
+
continue
|
129 |
+
|
130 |
+
for name, module in embedder.wrapped.named_modules():
|
131 |
+
network_name = f'{i}_{name.replace(".", "_")}'
|
132 |
+
network_layer_mapping[network_name] = module
|
133 |
+
module.network_layer_name = network_name
|
134 |
+
else:
|
135 |
+
cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
|
136 |
+
|
137 |
+
for name, module in cond_stage_model.named_modules():
|
138 |
+
network_name = name.replace(".", "_")
|
139 |
+
network_layer_mapping[network_name] = module
|
140 |
+
module.network_layer_name = network_name
|
141 |
+
|
142 |
+
for name, module in shared.sd_model.model.named_modules():
|
143 |
+
network_name = name.replace(".", "_")
|
144 |
+
network_layer_mapping[network_name] = module
|
145 |
+
module.network_layer_name = network_name
|
146 |
+
|
147 |
+
sd_model.network_layer_mapping = network_layer_mapping
|
148 |
+
|
149 |
+
|
150 |
+
class BundledTIHash(str):
|
151 |
+
def __init__(self, hash_str):
|
152 |
+
self.hash = hash_str
|
153 |
+
|
154 |
+
def __str__(self):
|
155 |
+
return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
|
156 |
+
|
157 |
+
|
158 |
+
def load_network(name, network_on_disk):
|
159 |
+
net = network.Network(name, network_on_disk)
|
160 |
+
net.mtime = os.path.getmtime(network_on_disk.filename)
|
161 |
+
|
162 |
+
sd = sd_models.read_state_dict(network_on_disk.filename)
|
163 |
+
|
164 |
+
# this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
|
165 |
+
if not hasattr(shared.sd_model, 'network_layer_mapping'):
|
166 |
+
assign_network_names_to_compvis_modules(shared.sd_model)
|
167 |
+
|
168 |
+
keys_failed_to_match = {}
|
169 |
+
is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
|
170 |
+
if hasattr(shared.sd_model, 'diffusers_weight_map'):
|
171 |
+
diffusers_weight_map = shared.sd_model.diffusers_weight_map
|
172 |
+
elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
|
173 |
+
diffusers_weight_map = {}
|
174 |
+
for k, v in shared.sd_model.diffusers_weight_mapping():
|
175 |
+
diffusers_weight_map[k] = v
|
176 |
+
shared.sd_model.diffusers_weight_map = diffusers_weight_map
|
177 |
+
else:
|
178 |
+
diffusers_weight_map = None
|
179 |
+
|
180 |
+
matched_networks = {}
|
181 |
+
bundle_embeddings = {}
|
182 |
+
|
183 |
+
for key_network, weight in sd.items():
|
184 |
+
|
185 |
+
if diffusers_weight_map:
|
186 |
+
key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
|
187 |
+
network_part = network_name + '.' + network_weight
|
188 |
+
else:
|
189 |
+
key_network_without_network_parts, _, network_part = key_network.partition(".")
|
190 |
+
|
191 |
+
if key_network_without_network_parts == "bundle_emb":
|
192 |
+
emb_name, vec_name = network_part.split(".", 1)
|
193 |
+
emb_dict = bundle_embeddings.get(emb_name, {})
|
194 |
+
if vec_name.split('.')[0] == 'string_to_param':
|
195 |
+
_, k2 = vec_name.split('.', 1)
|
196 |
+
emb_dict['string_to_param'] = {k2: weight}
|
197 |
+
else:
|
198 |
+
emb_dict[vec_name] = weight
|
199 |
+
bundle_embeddings[emb_name] = emb_dict
|
200 |
+
|
201 |
+
if diffusers_weight_map:
|
202 |
+
key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
|
203 |
+
else:
|
204 |
+
key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
|
205 |
+
|
206 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
207 |
+
|
208 |
+
if sd_module is None:
|
209 |
+
m = re_x_proj.match(key)
|
210 |
+
if m:
|
211 |
+
sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
|
212 |
+
|
213 |
+
# SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
|
214 |
+
if sd_module is None and "lora_unet" in key_network_without_network_parts:
|
215 |
+
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
216 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
217 |
+
elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
|
218 |
+
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
219 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
220 |
+
|
221 |
+
# some SD1 Loras also have correct compvis keys
|
222 |
+
if sd_module is None:
|
223 |
+
key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
|
224 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
225 |
+
|
226 |
+
# kohya_ss OFT module
|
227 |
+
elif sd_module is None and "oft_unet" in key_network_without_network_parts:
|
228 |
+
key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
|
229 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
230 |
+
|
231 |
+
# KohakuBlueLeaf OFT module
|
232 |
+
if sd_module is None and "oft_diag" in key:
|
233 |
+
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
|
234 |
+
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
|
235 |
+
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
|
236 |
+
|
237 |
+
if sd_module is None:
|
238 |
+
keys_failed_to_match[key_network] = key
|
239 |
+
continue
|
240 |
+
|
241 |
+
if key not in matched_networks:
|
242 |
+
matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
|
243 |
+
|
244 |
+
matched_networks[key].w[network_part] = weight
|
245 |
+
|
246 |
+
for key, weights in matched_networks.items():
|
247 |
+
net_module = None
|
248 |
+
for nettype in module_types:
|
249 |
+
net_module = nettype.create_module(net, weights)
|
250 |
+
if net_module is not None:
|
251 |
+
break
|
252 |
+
|
253 |
+
if net_module is None:
|
254 |
+
raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
|
255 |
+
|
256 |
+
net.modules[key] = net_module
|
257 |
+
|
258 |
+
embeddings = {}
|
259 |
+
for emb_name, data in bundle_embeddings.items():
|
260 |
+
embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
|
261 |
+
embedding.loaded = None
|
262 |
+
embedding.shorthash = BundledTIHash(name)
|
263 |
+
embeddings[emb_name] = embedding
|
264 |
+
|
265 |
+
net.bundle_embeddings = embeddings
|
266 |
+
|
267 |
+
if keys_failed_to_match:
|
268 |
+
logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
|
269 |
+
|
270 |
+
return net
|
271 |
+
|
272 |
+
|
273 |
+
def purge_networks_from_memory():
|
274 |
+
while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
|
275 |
+
name = next(iter(networks_in_memory))
|
276 |
+
networks_in_memory.pop(name, None)
|
277 |
+
|
278 |
+
devices.torch_gc()
|
279 |
+
|
280 |
+
|
281 |
+
def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
|
282 |
+
emb_db = sd_hijack.model_hijack.embedding_db
|
283 |
+
already_loaded = {}
|
284 |
+
|
285 |
+
for net in loaded_networks:
|
286 |
+
if net.name in names:
|
287 |
+
already_loaded[net.name] = net
|
288 |
+
for emb_name, embedding in net.bundle_embeddings.items():
|
289 |
+
if embedding.loaded:
|
290 |
+
emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
|
291 |
+
|
292 |
+
loaded_networks.clear()
|
293 |
+
|
294 |
+
unavailable_networks = []
|
295 |
+
for name in names:
|
296 |
+
if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
|
297 |
+
unavailable_networks.append(name)
|
298 |
+
elif available_network_aliases.get(name) is None:
|
299 |
+
unavailable_networks.append(name)
|
300 |
+
|
301 |
+
if unavailable_networks:
|
302 |
+
update_available_networks_by_names(unavailable_networks)
|
303 |
+
|
304 |
+
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
305 |
+
if any(x is None for x in networks_on_disk):
|
306 |
+
list_available_networks()
|
307 |
+
|
308 |
+
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
309 |
+
|
310 |
+
failed_to_load_networks = []
|
311 |
+
|
312 |
+
for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
|
313 |
+
net = already_loaded.get(name, None)
|
314 |
+
|
315 |
+
if network_on_disk is not None:
|
316 |
+
if net is None:
|
317 |
+
net = networks_in_memory.get(name)
|
318 |
+
|
319 |
+
if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
|
320 |
+
try:
|
321 |
+
net = load_network(name, network_on_disk)
|
322 |
+
|
323 |
+
networks_in_memory.pop(name, None)
|
324 |
+
networks_in_memory[name] = net
|
325 |
+
except Exception as e:
|
326 |
+
errors.display(e, f"loading network {network_on_disk.filename}")
|
327 |
+
continue
|
328 |
+
|
329 |
+
net.mentioned_name = name
|
330 |
+
|
331 |
+
network_on_disk.read_hash()
|
332 |
+
|
333 |
+
if net is None:
|
334 |
+
failed_to_load_networks.append(name)
|
335 |
+
logging.info(f"Couldn't find network with name {name}")
|
336 |
+
continue
|
337 |
+
|
338 |
+
net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
|
339 |
+
net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
|
340 |
+
net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
|
341 |
+
loaded_networks.append(net)
|
342 |
+
|
343 |
+
for emb_name, embedding in net.bundle_embeddings.items():
|
344 |
+
if embedding.loaded is None and emb_name in emb_db.word_embeddings:
|
345 |
+
logger.warning(
|
346 |
+
f'Skip bundle embedding: "{emb_name}"'
|
347 |
+
' as it was already loaded from embeddings folder'
|
348 |
+
)
|
349 |
+
continue
|
350 |
+
|
351 |
+
embedding.loaded = False
|
352 |
+
if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
|
353 |
+
embedding.loaded = True
|
354 |
+
emb_db.register_embedding(embedding, shared.sd_model)
|
355 |
+
else:
|
356 |
+
emb_db.skipped_embeddings[name] = embedding
|
357 |
+
|
358 |
+
if failed_to_load_networks:
|
359 |
+
lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
|
360 |
+
sd_hijack.model_hijack.comments.append(lora_not_found_message)
|
361 |
+
if shared.opts.lora_not_found_warning_console:
|
362 |
+
print(f'\n{lora_not_found_message}\n')
|
363 |
+
if shared.opts.lora_not_found_gradio_warning:
|
364 |
+
gr.Warning(lora_not_found_message)
|
365 |
+
|
366 |
+
purge_networks_from_memory()
|
367 |
+
|
368 |
+
|
369 |
+
def allowed_layer_without_weight(layer):
|
370 |
+
if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
|
371 |
+
return True
|
372 |
+
|
373 |
+
return False
|
374 |
+
|
375 |
+
|
376 |
+
def store_weights_backup(weight):
|
377 |
+
if weight is None:
|
378 |
+
return None
|
379 |
+
|
380 |
+
return weight.to(devices.cpu, copy=True)
|
381 |
+
|
382 |
+
|
383 |
+
def restore_weights_backup(obj, field, weight):
|
384 |
+
if weight is None:
|
385 |
+
setattr(obj, field, None)
|
386 |
+
return
|
387 |
+
|
388 |
+
getattr(obj, field).copy_(weight)
|
389 |
+
|
390 |
+
|
391 |
+
def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
392 |
+
weights_backup = getattr(self, "network_weights_backup", None)
|
393 |
+
bias_backup = getattr(self, "network_bias_backup", None)
|
394 |
+
|
395 |
+
if weights_backup is None and bias_backup is None:
|
396 |
+
return
|
397 |
+
|
398 |
+
if weights_backup is not None:
|
399 |
+
if isinstance(self, torch.nn.MultiheadAttention):
|
400 |
+
restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
|
401 |
+
restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
|
402 |
+
else:
|
403 |
+
restore_weights_backup(self, 'weight', weights_backup)
|
404 |
+
|
405 |
+
if isinstance(self, torch.nn.MultiheadAttention):
|
406 |
+
restore_weights_backup(self.out_proj, 'bias', bias_backup)
|
407 |
+
else:
|
408 |
+
restore_weights_backup(self, 'bias', bias_backup)
|
409 |
+
|
410 |
+
|
411 |
+
def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
|
412 |
+
"""
|
413 |
+
Applies the currently selected set of networks to the weights of torch layer self.
|
414 |
+
If weights already have this particular set of networks applied, does nothing.
|
415 |
+
If not, restores original weights from backup and alters weights according to networks.
|
416 |
+
"""
|
417 |
+
|
418 |
+
network_layer_name = getattr(self, 'network_layer_name', None)
|
419 |
+
if network_layer_name is None:
|
420 |
+
return
|
421 |
+
|
422 |
+
current_names = getattr(self, "network_current_names", ())
|
423 |
+
wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
|
424 |
+
|
425 |
+
weights_backup = getattr(self, "network_weights_backup", None)
|
426 |
+
if weights_backup is None and wanted_names != ():
|
427 |
+
if current_names != () and not allowed_layer_without_weight(self):
|
428 |
+
raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
|
429 |
+
|
430 |
+
if isinstance(self, torch.nn.MultiheadAttention):
|
431 |
+
weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
|
432 |
+
else:
|
433 |
+
weights_backup = store_weights_backup(self.weight)
|
434 |
+
|
435 |
+
self.network_weights_backup = weights_backup
|
436 |
+
|
437 |
+
bias_backup = getattr(self, "network_bias_backup", None)
|
438 |
+
if bias_backup is None and wanted_names != ():
|
439 |
+
if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
|
440 |
+
bias_backup = store_weights_backup(self.out_proj.bias)
|
441 |
+
elif getattr(self, 'bias', None) is not None:
|
442 |
+
bias_backup = store_weights_backup(self.bias)
|
443 |
+
else:
|
444 |
+
bias_backup = None
|
445 |
+
|
446 |
+
# Unlike weight which always has value, some modules don't have bias.
|
447 |
+
# Only report if bias is not None and current bias are not unchanged.
|
448 |
+
if bias_backup is not None and current_names != ():
|
449 |
+
raise RuntimeError("no backup bias found and current bias are not unchanged")
|
450 |
+
|
451 |
+
self.network_bias_backup = bias_backup
|
452 |
+
|
453 |
+
if current_names != wanted_names:
|
454 |
+
network_restore_weights_from_backup(self)
|
455 |
+
|
456 |
+
for net in loaded_networks:
|
457 |
+
module = net.modules.get(network_layer_name, None)
|
458 |
+
if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
|
459 |
+
try:
|
460 |
+
with torch.no_grad():
|
461 |
+
if getattr(self, 'fp16_weight', None) is None:
|
462 |
+
weight = self.weight
|
463 |
+
bias = self.bias
|
464 |
+
else:
|
465 |
+
weight = self.fp16_weight.clone().to(self.weight.device)
|
466 |
+
bias = getattr(self, 'fp16_bias', None)
|
467 |
+
if bias is not None:
|
468 |
+
bias = bias.clone().to(self.bias.device)
|
469 |
+
updown, ex_bias = module.calc_updown(weight)
|
470 |
+
|
471 |
+
if len(weight.shape) == 4 and weight.shape[1] == 9:
|
472 |
+
# inpainting model. zero pad updown to make channel[1] 4 to 9
|
473 |
+
updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
|
474 |
+
|
475 |
+
self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
|
476 |
+
if ex_bias is not None and hasattr(self, 'bias'):
|
477 |
+
if self.bias is None:
|
478 |
+
self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
|
479 |
+
else:
|
480 |
+
self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
|
481 |
+
except RuntimeError as e:
|
482 |
+
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
483 |
+
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
484 |
+
|
485 |
+
continue
|
486 |
+
|
487 |
+
module_q = net.modules.get(network_layer_name + "_q_proj", None)
|
488 |
+
module_k = net.modules.get(network_layer_name + "_k_proj", None)
|
489 |
+
module_v = net.modules.get(network_layer_name + "_v_proj", None)
|
490 |
+
module_out = net.modules.get(network_layer_name + "_out_proj", None)
|
491 |
+
|
492 |
+
if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
|
493 |
+
try:
|
494 |
+
with torch.no_grad():
|
495 |
+
# Send "real" orig_weight into MHA's lora module
|
496 |
+
qw, kw, vw = self.in_proj_weight.chunk(3, 0)
|
497 |
+
updown_q, _ = module_q.calc_updown(qw)
|
498 |
+
updown_k, _ = module_k.calc_updown(kw)
|
499 |
+
updown_v, _ = module_v.calc_updown(vw)
|
500 |
+
del qw, kw, vw
|
501 |
+
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
502 |
+
updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
|
503 |
+
|
504 |
+
self.in_proj_weight += updown_qkv
|
505 |
+
self.out_proj.weight += updown_out
|
506 |
+
if ex_bias is not None:
|
507 |
+
if self.out_proj.bias is None:
|
508 |
+
self.out_proj.bias = torch.nn.Parameter(ex_bias)
|
509 |
+
else:
|
510 |
+
self.out_proj.bias += ex_bias
|
511 |
+
|
512 |
+
except RuntimeError as e:
|
513 |
+
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
514 |
+
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
515 |
+
|
516 |
+
continue
|
517 |
+
|
518 |
+
if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
|
519 |
+
try:
|
520 |
+
with torch.no_grad():
|
521 |
+
# Send "real" orig_weight into MHA's lora module
|
522 |
+
qw, kw, vw = self.weight.chunk(3, 0)
|
523 |
+
updown_q, _ = module_q.calc_updown(qw)
|
524 |
+
updown_k, _ = module_k.calc_updown(kw)
|
525 |
+
updown_v, _ = module_v.calc_updown(vw)
|
526 |
+
del qw, kw, vw
|
527 |
+
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
|
528 |
+
self.weight += updown_qkv
|
529 |
+
|
530 |
+
except RuntimeError as e:
|
531 |
+
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
|
532 |
+
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
533 |
+
|
534 |
+
continue
|
535 |
+
|
536 |
+
if module is None:
|
537 |
+
continue
|
538 |
+
|
539 |
+
logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
|
540 |
+
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
|
541 |
+
|
542 |
+
self.network_current_names = wanted_names
|
543 |
+
|
544 |
+
|
545 |
+
def network_forward(org_module, input, original_forward):
|
546 |
+
"""
|
547 |
+
Old way of applying Lora by executing operations during layer's forward.
|
548 |
+
Stacking many loras this way results in big performance degradation.
|
549 |
+
"""
|
550 |
+
|
551 |
+
if len(loaded_networks) == 0:
|
552 |
+
return original_forward(org_module, input)
|
553 |
+
|
554 |
+
input = devices.cond_cast_unet(input)
|
555 |
+
|
556 |
+
network_restore_weights_from_backup(org_module)
|
557 |
+
network_reset_cached_weight(org_module)
|
558 |
+
|
559 |
+
y = original_forward(org_module, input)
|
560 |
+
|
561 |
+
network_layer_name = getattr(org_module, 'network_layer_name', None)
|
562 |
+
for lora in loaded_networks:
|
563 |
+
module = lora.modules.get(network_layer_name, None)
|
564 |
+
if module is None:
|
565 |
+
continue
|
566 |
+
|
567 |
+
y = module.forward(input, y)
|
568 |
+
|
569 |
+
return y
|
570 |
+
|
571 |
+
|
572 |
+
def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
|
573 |
+
self.network_current_names = ()
|
574 |
+
self.network_weights_backup = None
|
575 |
+
self.network_bias_backup = None
|
576 |
+
|
577 |
+
|
578 |
+
def network_Linear_forward(self, input):
|
579 |
+
if shared.opts.lora_functional:
|
580 |
+
return network_forward(self, input, originals.Linear_forward)
|
581 |
+
|
582 |
+
network_apply_weights(self)
|
583 |
+
|
584 |
+
return originals.Linear_forward(self, input)
|
585 |
+
|
586 |
+
|
587 |
+
def network_Linear_load_state_dict(self, *args, **kwargs):
|
588 |
+
network_reset_cached_weight(self)
|
589 |
+
|
590 |
+
return originals.Linear_load_state_dict(self, *args, **kwargs)
|
591 |
+
|
592 |
+
|
593 |
+
def network_Conv2d_forward(self, input):
|
594 |
+
if shared.opts.lora_functional:
|
595 |
+
return network_forward(self, input, originals.Conv2d_forward)
|
596 |
+
|
597 |
+
network_apply_weights(self)
|
598 |
+
|
599 |
+
return originals.Conv2d_forward(self, input)
|
600 |
+
|
601 |
+
|
602 |
+
def network_Conv2d_load_state_dict(self, *args, **kwargs):
|
603 |
+
network_reset_cached_weight(self)
|
604 |
+
|
605 |
+
return originals.Conv2d_load_state_dict(self, *args, **kwargs)
|
606 |
+
|
607 |
+
|
608 |
+
def network_GroupNorm_forward(self, input):
|
609 |
+
if shared.opts.lora_functional:
|
610 |
+
return network_forward(self, input, originals.GroupNorm_forward)
|
611 |
+
|
612 |
+
network_apply_weights(self)
|
613 |
+
|
614 |
+
return originals.GroupNorm_forward(self, input)
|
615 |
+
|
616 |
+
|
617 |
+
def network_GroupNorm_load_state_dict(self, *args, **kwargs):
|
618 |
+
network_reset_cached_weight(self)
|
619 |
+
|
620 |
+
return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
|
621 |
+
|
622 |
+
|
623 |
+
def network_LayerNorm_forward(self, input):
|
624 |
+
if shared.opts.lora_functional:
|
625 |
+
return network_forward(self, input, originals.LayerNorm_forward)
|
626 |
+
|
627 |
+
network_apply_weights(self)
|
628 |
+
|
629 |
+
return originals.LayerNorm_forward(self, input)
|
630 |
+
|
631 |
+
|
632 |
+
def network_LayerNorm_load_state_dict(self, *args, **kwargs):
|
633 |
+
network_reset_cached_weight(self)
|
634 |
+
|
635 |
+
return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
|
636 |
+
|
637 |
+
|
638 |
+
def network_MultiheadAttention_forward(self, *args, **kwargs):
|
639 |
+
network_apply_weights(self)
|
640 |
+
|
641 |
+
return originals.MultiheadAttention_forward(self, *args, **kwargs)
|
642 |
+
|
643 |
+
|
644 |
+
def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
|
645 |
+
network_reset_cached_weight(self)
|
646 |
+
|
647 |
+
return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
|
648 |
+
|
649 |
+
|
650 |
+
def process_network_files(names: list[str] | None = None):
|
651 |
+
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
652 |
+
candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
653 |
+
for filename in candidates:
|
654 |
+
if os.path.isdir(filename):
|
655 |
+
continue
|
656 |
+
name = os.path.splitext(os.path.basename(filename))[0]
|
657 |
+
# if names is provided, only load networks with names in the list
|
658 |
+
if names and name not in names:
|
659 |
+
continue
|
660 |
+
try:
|
661 |
+
entry = network.NetworkOnDisk(name, filename)
|
662 |
+
except OSError: # should catch FileNotFoundError and PermissionError etc.
|
663 |
+
errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
|
664 |
+
continue
|
665 |
+
|
666 |
+
available_networks[name] = entry
|
667 |
+
|
668 |
+
if entry.alias in available_network_aliases:
|
669 |
+
forbidden_network_aliases[entry.alias.lower()] = 1
|
670 |
+
|
671 |
+
available_network_aliases[name] = entry
|
672 |
+
available_network_aliases[entry.alias] = entry
|
673 |
+
|
674 |
+
|
675 |
+
def update_available_networks_by_names(names: list[str]):
|
676 |
+
process_network_files(names)
|
677 |
+
|
678 |
+
|
679 |
+
def list_available_networks():
|
680 |
+
available_networks.clear()
|
681 |
+
available_network_aliases.clear()
|
682 |
+
forbidden_network_aliases.clear()
|
683 |
+
available_network_hash_lookup.clear()
|
684 |
+
forbidden_network_aliases.update({"none": 1, "Addams": 1})
|
685 |
+
|
686 |
+
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
|
687 |
+
|
688 |
+
process_network_files()
|
689 |
+
|
690 |
+
|
691 |
+
re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
|
692 |
+
|
693 |
+
|
694 |
+
def infotext_pasted(infotext, params):
|
695 |
+
if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
|
696 |
+
return # if the other extension is active, it will handle those fields, no need to do anything
|
697 |
+
|
698 |
+
added = []
|
699 |
+
|
700 |
+
for k in params:
|
701 |
+
if not k.startswith("AddNet Model "):
|
702 |
+
continue
|
703 |
+
|
704 |
+
num = k[13:]
|
705 |
+
|
706 |
+
if params.get("AddNet Module " + num) != "LoRA":
|
707 |
+
continue
|
708 |
+
|
709 |
+
name = params.get("AddNet Model " + num)
|
710 |
+
if name is None:
|
711 |
+
continue
|
712 |
+
|
713 |
+
m = re_network_name.match(name)
|
714 |
+
if m:
|
715 |
+
name = m.group(1)
|
716 |
+
|
717 |
+
multiplier = params.get("AddNet Weight A " + num, "1.0")
|
718 |
+
|
719 |
+
added.append(f"<lora:{name}:{multiplier}>")
|
720 |
+
|
721 |
+
if added:
|
722 |
+
params["Prompt"] += "\n" + "".join(added)
|
723 |
+
|
724 |
+
|
725 |
+
originals: lora_patches.LoraPatches = None
|
726 |
+
|
727 |
+
extra_network_lora = None
|
728 |
+
|
729 |
+
available_networks = {}
|
730 |
+
available_network_aliases = {}
|
731 |
+
loaded_networks = []
|
732 |
+
loaded_bundle_embeddings = {}
|
733 |
+
networks_in_memory = {}
|
734 |
+
available_network_hash_lookup = {}
|
735 |
+
forbidden_network_aliases = {}
|
736 |
+
|
737 |
+
list_available_networks()
|
extensions-builtin/Lora/preload.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from modules import paths
|
3 |
+
from modules.paths_internal import normalized_filepath
|
4 |
+
|
5 |
+
|
6 |
+
def preload(parser):
|
7 |
+
parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
8 |
+
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also use --lyco-dir).", default=os.path.join(paths.models_path, 'LyCORIS'))
|
extensions-builtin/Lora/scripts/lora_script.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
from fastapi import FastAPI
|
5 |
+
|
6 |
+
import network
|
7 |
+
import networks
|
8 |
+
import lora # noqa:F401
|
9 |
+
import lora_patches
|
10 |
+
import extra_networks_lora
|
11 |
+
import ui_extra_networks_lora
|
12 |
+
from modules import script_callbacks, ui_extra_networks, extra_networks, shared
|
13 |
+
|
14 |
+
|
15 |
+
def unload():
|
16 |
+
networks.originals.undo()
|
17 |
+
|
18 |
+
|
19 |
+
def before_ui():
|
20 |
+
ui_extra_networks.register_page(ui_extra_networks_lora.ExtraNetworksPageLora())
|
21 |
+
|
22 |
+
networks.extra_network_lora = extra_networks_lora.ExtraNetworkLora()
|
23 |
+
extra_networks.register_extra_network(networks.extra_network_lora)
|
24 |
+
extra_networks.register_extra_network_alias(networks.extra_network_lora, "lyco")
|
25 |
+
|
26 |
+
|
27 |
+
networks.originals = lora_patches.LoraPatches()
|
28 |
+
|
29 |
+
script_callbacks.on_model_loaded(networks.assign_network_names_to_compvis_modules)
|
30 |
+
script_callbacks.on_script_unloaded(unload)
|
31 |
+
script_callbacks.on_before_ui(before_ui)
|
32 |
+
script_callbacks.on_infotext_pasted(networks.infotext_pasted)
|
33 |
+
|
34 |
+
|
35 |
+
shared.options_templates.update(shared.options_section(('extra_networks', "Extra Networks"), {
|
36 |
+
"sd_lora": shared.OptionInfo("None", "Add network to prompt", gr.Dropdown, lambda: {"choices": ["None", *networks.available_networks]}, refresh=networks.list_available_networks),
|
37 |
+
"lora_preferred_name": shared.OptionInfo("Alias from file", "When adding to prompt, refer to Lora by", gr.Radio, {"choices": ["Alias from file", "Filename"]}),
|
38 |
+
"lora_add_hashes_to_infotext": shared.OptionInfo(True, "Add Lora hashes to infotext"),
|
39 |
+
"lora_bundled_ti_to_infotext": shared.OptionInfo(True, "Add Lora name as TI hashes for bundled Textual Inversion").info('"Add Textual Inversion hashes to infotext" needs to be enabled'),
|
40 |
+
"lora_show_all": shared.OptionInfo(False, "Always show all networks on the Lora page").info("otherwise, those detected as for incompatible version of Stable Diffusion will be hidden"),
|
41 |
+
"lora_hide_unknown_for_versions": shared.OptionInfo([], "Hide networks of unknown versions for model versions", gr.CheckboxGroup, {"choices": ["SD1", "SD2", "SDXL"]}),
|
42 |
+
"lora_in_memory_limit": shared.OptionInfo(0, "Number of Lora networks to keep cached in memory", gr.Number, {"precision": 0}),
|
43 |
+
"lora_not_found_warning_console": shared.OptionInfo(False, "Lora not found warning in console"),
|
44 |
+
"lora_not_found_gradio_warning": shared.OptionInfo(False, "Lora not found warning popup in webui"),
|
45 |
+
}))
|
46 |
+
|
47 |
+
|
48 |
+
shared.options_templates.update(shared.options_section(('compatibility', "Compatibility"), {
|
49 |
+
"lora_functional": shared.OptionInfo(False, "Lora/Networks: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension"),
|
50 |
+
}))
|
51 |
+
|
52 |
+
|
53 |
+
def create_lora_json(obj: network.NetworkOnDisk):
|
54 |
+
return {
|
55 |
+
"name": obj.name,
|
56 |
+
"alias": obj.alias,
|
57 |
+
"path": obj.filename,
|
58 |
+
"metadata": obj.metadata,
|
59 |
+
}
|
60 |
+
|
61 |
+
|
62 |
+
def api_networks(_: gr.Blocks, app: FastAPI):
|
63 |
+
@app.get("/sdapi/v1/loras")
|
64 |
+
async def get_loras():
|
65 |
+
return [create_lora_json(obj) for obj in networks.available_networks.values()]
|
66 |
+
|
67 |
+
@app.post("/sdapi/v1/refresh-loras")
|
68 |
+
async def refresh_loras():
|
69 |
+
return networks.list_available_networks()
|
70 |
+
|
71 |
+
|
72 |
+
script_callbacks.on_app_started(api_networks)
|
73 |
+
|
74 |
+
re_lora = re.compile("<lora:([^:]+):")
|
75 |
+
|
76 |
+
|
77 |
+
def infotext_pasted(infotext, d):
|
78 |
+
hashes = d.get("Lora hashes")
|
79 |
+
if not hashes:
|
80 |
+
return
|
81 |
+
|
82 |
+
hashes = [x.strip().split(':', 1) for x in hashes.split(",")]
|
83 |
+
hashes = {x[0].strip().replace(",", ""): x[1].strip() for x in hashes}
|
84 |
+
|
85 |
+
def network_replacement(m):
|
86 |
+
alias = m.group(1)
|
87 |
+
shorthash = hashes.get(alias)
|
88 |
+
if shorthash is None:
|
89 |
+
return m.group(0)
|
90 |
+
|
91 |
+
network_on_disk = networks.available_network_hash_lookup.get(shorthash)
|
92 |
+
if network_on_disk is None:
|
93 |
+
return m.group(0)
|
94 |
+
|
95 |
+
return f'<lora:{network_on_disk.get_alias()}:'
|
96 |
+
|
97 |
+
d["Prompt"] = re.sub(re_lora, network_replacement, d["Prompt"])
|
98 |
+
|
99 |
+
|
100 |
+
script_callbacks.on_infotext_pasted(infotext_pasted)
|
101 |
+
|
102 |
+
shared.opts.onchange("lora_in_memory_limit", networks.purge_networks_from_memory)
|
extensions-builtin/Lora/ui_edit_user_metadata.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import html
|
3 |
+
import random
|
4 |
+
|
5 |
+
import gradio as gr
|
6 |
+
import re
|
7 |
+
|
8 |
+
from modules import ui_extra_networks_user_metadata
|
9 |
+
|
10 |
+
|
11 |
+
def is_non_comma_tagset(tags):
|
12 |
+
average_tag_length = sum(len(x) for x in tags.keys()) / len(tags)
|
13 |
+
|
14 |
+
return average_tag_length >= 16
|
15 |
+
|
16 |
+
|
17 |
+
re_word = re.compile(r"[-_\w']+")
|
18 |
+
re_comma = re.compile(r" *, *")
|
19 |
+
|
20 |
+
|
21 |
+
def build_tags(metadata):
|
22 |
+
tags = {}
|
23 |
+
|
24 |
+
ss_tag_frequency = metadata.get("ss_tag_frequency", {})
|
25 |
+
if ss_tag_frequency is not None and hasattr(ss_tag_frequency, 'items'):
|
26 |
+
for _, tags_dict in ss_tag_frequency.items():
|
27 |
+
for tag, tag_count in tags_dict.items():
|
28 |
+
tag = tag.strip()
|
29 |
+
tags[tag] = tags.get(tag, 0) + int(tag_count)
|
30 |
+
|
31 |
+
if tags and is_non_comma_tagset(tags):
|
32 |
+
new_tags = {}
|
33 |
+
|
34 |
+
for text, text_count in tags.items():
|
35 |
+
for word in re.findall(re_word, text):
|
36 |
+
if len(word) < 3:
|
37 |
+
continue
|
38 |
+
|
39 |
+
new_tags[word] = new_tags.get(word, 0) + text_count
|
40 |
+
|
41 |
+
tags = new_tags
|
42 |
+
|
43 |
+
ordered_tags = sorted(tags.keys(), key=tags.get, reverse=True)
|
44 |
+
|
45 |
+
return [(tag, tags[tag]) for tag in ordered_tags]
|
46 |
+
|
47 |
+
|
48 |
+
class LoraUserMetadataEditor(ui_extra_networks_user_metadata.UserMetadataEditor):
|
49 |
+
def __init__(self, ui, tabname, page):
|
50 |
+
super().__init__(ui, tabname, page)
|
51 |
+
|
52 |
+
self.select_sd_version = None
|
53 |
+
|
54 |
+
self.taginfo = None
|
55 |
+
self.edit_activation_text = None
|
56 |
+
self.slider_preferred_weight = None
|
57 |
+
self.edit_notes = None
|
58 |
+
|
59 |
+
def save_lora_user_metadata(self, name, desc, sd_version, activation_text, preferred_weight, negative_text, notes):
|
60 |
+
user_metadata = self.get_user_metadata(name)
|
61 |
+
user_metadata["description"] = desc
|
62 |
+
user_metadata["sd version"] = sd_version
|
63 |
+
user_metadata["activation text"] = activation_text
|
64 |
+
user_metadata["preferred weight"] = preferred_weight
|
65 |
+
user_metadata["negative text"] = negative_text
|
66 |
+
user_metadata["notes"] = notes
|
67 |
+
|
68 |
+
self.write_user_metadata(name, user_metadata)
|
69 |
+
|
70 |
+
def get_metadata_table(self, name):
|
71 |
+
table = super().get_metadata_table(name)
|
72 |
+
item = self.page.items.get(name, {})
|
73 |
+
metadata = item.get("metadata") or {}
|
74 |
+
|
75 |
+
keys = {
|
76 |
+
'ss_output_name': "Output name:",
|
77 |
+
'ss_sd_model_name': "Model:",
|
78 |
+
'ss_clip_skip': "Clip skip:",
|
79 |
+
'ss_network_module': "Kohya module:",
|
80 |
+
}
|
81 |
+
|
82 |
+
for key, label in keys.items():
|
83 |
+
value = metadata.get(key, None)
|
84 |
+
if value is not None and str(value) != "None":
|
85 |
+
table.append((label, html.escape(value)))
|
86 |
+
|
87 |
+
ss_training_started_at = metadata.get('ss_training_started_at')
|
88 |
+
if ss_training_started_at:
|
89 |
+
table.append(("Date trained:", datetime.datetime.utcfromtimestamp(float(ss_training_started_at)).strftime('%Y-%m-%d %H:%M')))
|
90 |
+
|
91 |
+
ss_bucket_info = metadata.get("ss_bucket_info")
|
92 |
+
if ss_bucket_info and "buckets" in ss_bucket_info:
|
93 |
+
resolutions = {}
|
94 |
+
for _, bucket in ss_bucket_info["buckets"].items():
|
95 |
+
resolution = bucket["resolution"]
|
96 |
+
resolution = f'{resolution[1]}x{resolution[0]}'
|
97 |
+
|
98 |
+
resolutions[resolution] = resolutions.get(resolution, 0) + int(bucket["count"])
|
99 |
+
|
100 |
+
resolutions_list = sorted(resolutions.keys(), key=resolutions.get, reverse=True)
|
101 |
+
resolutions_text = html.escape(", ".join(resolutions_list[0:4]))
|
102 |
+
if len(resolutions) > 4:
|
103 |
+
resolutions_text += ", ..."
|
104 |
+
resolutions_text = f"<span title='{html.escape(', '.join(resolutions_list))}'>{resolutions_text}</span>"
|
105 |
+
|
106 |
+
table.append(('Resolutions:' if len(resolutions_list) > 1 else 'Resolution:', resolutions_text))
|
107 |
+
|
108 |
+
image_count = 0
|
109 |
+
for _, params in metadata.get("ss_dataset_dirs", {}).items():
|
110 |
+
image_count += int(params.get("img_count", 0))
|
111 |
+
|
112 |
+
if image_count:
|
113 |
+
table.append(("Dataset size:", image_count))
|
114 |
+
|
115 |
+
return table
|
116 |
+
|
117 |
+
def put_values_into_components(self, name):
|
118 |
+
user_metadata = self.get_user_metadata(name)
|
119 |
+
values = super().put_values_into_components(name)
|
120 |
+
|
121 |
+
item = self.page.items.get(name, {})
|
122 |
+
metadata = item.get("metadata") or {}
|
123 |
+
|
124 |
+
tags = build_tags(metadata)
|
125 |
+
gradio_tags = [(tag, str(count)) for tag, count in tags[0:24]]
|
126 |
+
|
127 |
+
return [
|
128 |
+
*values[0:5],
|
129 |
+
item.get("sd_version", "Unknown"),
|
130 |
+
gr.HighlightedText.update(value=gradio_tags, visible=True if tags else False),
|
131 |
+
user_metadata.get('activation text', ''),
|
132 |
+
float(user_metadata.get('preferred weight', 0.0)),
|
133 |
+
user_metadata.get('negative text', ''),
|
134 |
+
gr.update(visible=True if tags else False),
|
135 |
+
gr.update(value=self.generate_random_prompt_from_tags(tags), visible=True if tags else False),
|
136 |
+
]
|
137 |
+
|
138 |
+
def generate_random_prompt(self, name):
|
139 |
+
item = self.page.items.get(name, {})
|
140 |
+
metadata = item.get("metadata") or {}
|
141 |
+
tags = build_tags(metadata)
|
142 |
+
|
143 |
+
return self.generate_random_prompt_from_tags(tags)
|
144 |
+
|
145 |
+
def generate_random_prompt_from_tags(self, tags):
|
146 |
+
max_count = None
|
147 |
+
res = []
|
148 |
+
for tag, count in tags:
|
149 |
+
if not max_count:
|
150 |
+
max_count = count
|
151 |
+
|
152 |
+
v = random.random() * max_count
|
153 |
+
if count > v:
|
154 |
+
for x in "({[]})":
|
155 |
+
tag = tag.replace(x, '\\' + x)
|
156 |
+
res.append(tag)
|
157 |
+
|
158 |
+
return ", ".join(sorted(res))
|
159 |
+
|
160 |
+
def create_extra_default_items_in_left_column(self):
|
161 |
+
|
162 |
+
# this would be a lot better as gr.Radio but I can't make it work
|
163 |
+
self.select_sd_version = gr.Dropdown(['SD1', 'SD2', 'SDXL', 'Unknown'], value='Unknown', label='Stable Diffusion version', interactive=True)
|
164 |
+
|
165 |
+
def create_editor(self):
|
166 |
+
self.create_default_editor_elems()
|
167 |
+
|
168 |
+
self.taginfo = gr.HighlightedText(label="Training dataset tags")
|
169 |
+
self.edit_activation_text = gr.Text(label='Activation text', info="Will be added to prompt along with Lora")
|
170 |
+
self.slider_preferred_weight = gr.Slider(label='Preferred weight', info="Set to 0 to disable", minimum=0.0, maximum=2.0, step=0.01)
|
171 |
+
self.edit_negative_text = gr.Text(label='Negative prompt', info="Will be added to negative prompts")
|
172 |
+
with gr.Row() as row_random_prompt:
|
173 |
+
with gr.Column(scale=8):
|
174 |
+
random_prompt = gr.Textbox(label='Random prompt', lines=4, max_lines=4, interactive=False)
|
175 |
+
|
176 |
+
with gr.Column(scale=1, min_width=120):
|
177 |
+
generate_random_prompt = gr.Button('Generate', size="lg", scale=1)
|
178 |
+
|
179 |
+
self.edit_notes = gr.TextArea(label='Notes', lines=4)
|
180 |
+
|
181 |
+
generate_random_prompt.click(fn=self.generate_random_prompt, inputs=[self.edit_name_input], outputs=[random_prompt], show_progress=False)
|
182 |
+
|
183 |
+
def select_tag(activation_text, evt: gr.SelectData):
|
184 |
+
tag = evt.value[0]
|
185 |
+
|
186 |
+
words = re.split(re_comma, activation_text)
|
187 |
+
if tag in words:
|
188 |
+
words = [x for x in words if x != tag and x.strip()]
|
189 |
+
return ", ".join(words)
|
190 |
+
|
191 |
+
return activation_text + ", " + tag if activation_text else tag
|
192 |
+
|
193 |
+
self.taginfo.select(fn=select_tag, inputs=[self.edit_activation_text], outputs=[self.edit_activation_text], show_progress=False)
|
194 |
+
|
195 |
+
self.create_default_buttons()
|
196 |
+
|
197 |
+
viewed_components = [
|
198 |
+
self.edit_name,
|
199 |
+
self.edit_description,
|
200 |
+
self.html_filedata,
|
201 |
+
self.html_preview,
|
202 |
+
self.edit_notes,
|
203 |
+
self.select_sd_version,
|
204 |
+
self.taginfo,
|
205 |
+
self.edit_activation_text,
|
206 |
+
self.slider_preferred_weight,
|
207 |
+
self.edit_negative_text,
|
208 |
+
row_random_prompt,
|
209 |
+
random_prompt,
|
210 |
+
]
|
211 |
+
|
212 |
+
self.button_edit\
|
213 |
+
.click(fn=self.put_values_into_components, inputs=[self.edit_name_input], outputs=viewed_components)\
|
214 |
+
.then(fn=lambda: gr.update(visible=True), inputs=[], outputs=[self.box])
|
215 |
+
|
216 |
+
edited_components = [
|
217 |
+
self.edit_description,
|
218 |
+
self.select_sd_version,
|
219 |
+
self.edit_activation_text,
|
220 |
+
self.slider_preferred_weight,
|
221 |
+
self.edit_negative_text,
|
222 |
+
self.edit_notes,
|
223 |
+
]
|
224 |
+
|
225 |
+
|
226 |
+
self.setup_save_handler(self.button_save, self.save_lora_user_metadata, edited_components)
|