Spaces:
Runtime error
Runtime error
Commit
•
522606a
0
Parent(s):
Duplicate from YeOldHermit/Super-Resolution-Anime-Diffusion
Browse filesCo-authored-by: Elvin John Maat <[email protected]>
This view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +34 -0
- .gitignore +162 -0
- README.md +108 -0
- README_HG.md +12 -0
- Waifu2x/.gitattributes +1 -0
- Waifu2x/.gitignore +4 -0
- Waifu2x/Common.py +189 -0
- Waifu2x/Dataloader.py +215 -0
- Waifu2x/Img_to_Sqlite.py +115 -0
- Waifu2x/LICENSE +674 -0
- Waifu2x/Loss.py +44 -0
- Waifu2x/Models.py +316 -0
- Waifu2x/Readme.md +167 -0
- Waifu2x/__init__.py +9 -0
- Waifu2x/magnify.py +86 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_adam_checkpoint.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CARN_scheduler_last_iter.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/CRAN_V2_02_28_2019.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/ReadME.md +41 -0
- Waifu2x/model_check_points/CRAN_V2/test_loss.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/test_psnr.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/test_ssim.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_loss.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_psnr.pt +3 -0
- Waifu2x/model_check_points/CRAN_V2/train_ssim.pt +3 -0
- Waifu2x/train.py +174 -0
- Waifu2x/utils/Img_to_H5.py +50 -0
- Waifu2x/utils/__init__.py +8 -0
- Waifu2x/utils/cls.py +157 -0
- Waifu2x/utils/image_quality.py +173 -0
- Waifu2x/utils/prepare_images.py +120 -0
- app.py +344 -0
- diffusers/__init__.py +123 -0
- diffusers/commands/__init__.py +27 -0
- diffusers/commands/diffusers_cli.py +41 -0
- diffusers/commands/env.py +70 -0
- diffusers/configuration_utils.py +613 -0
- diffusers/dependency_versions_check.py +47 -0
- diffusers/dependency_versions_table.py +33 -0
- diffusers/dynamic_modules_utils.py +428 -0
- diffusers/experimental/README.md +5 -0
- diffusers/experimental/__init__.py +1 -0
- diffusers/experimental/rl/__init__.py +1 -0
- diffusers/experimental/rl/value_guided_sampling.py +130 -0
- diffusers/hub_utils.py +130 -0
- diffusers/modeling_flax_pytorch_utils.py +117 -0
- diffusers/modeling_flax_utils.py +526 -0
- diffusers/modeling_utils.py +764 -0
- diffusers/models/README.md +3 -0
.gitattributes
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# dev files
|
2 |
+
*.cache
|
3 |
+
*.dev.py
|
4 |
+
*.mv
|
5 |
+
state_dict/
|
6 |
+
integrated_datasets/
|
7 |
+
*.results
|
8 |
+
*.tokenizer
|
9 |
+
*.model
|
10 |
+
*.state_dict
|
11 |
+
*.config
|
12 |
+
*.args
|
13 |
+
*.zip
|
14 |
+
*.gz
|
15 |
+
*.bin
|
16 |
+
*.result.txt
|
17 |
+
*.DS_Store
|
18 |
+
*.tmp
|
19 |
+
*.args.txt
|
20 |
+
*.summary.txt
|
21 |
+
*.dat
|
22 |
+
*.graph
|
23 |
+
# Byte-compiled / optimized / DLL files
|
24 |
+
__pycache__/
|
25 |
+
*.py[cod]
|
26 |
+
*$py.class
|
27 |
+
*.pyc
|
28 |
+
experiments/
|
29 |
+
tests/
|
30 |
+
*.result.json
|
31 |
+
.idea/
|
32 |
+
imgs/
|
33 |
+
|
34 |
+
# Embedding
|
35 |
+
glove.840B.300d.txt
|
36 |
+
glove.42B.300d.txt
|
37 |
+
glove.twitter.27B.txt
|
38 |
+
|
39 |
+
# project main files
|
40 |
+
release_note.json
|
41 |
+
|
42 |
+
# C extensions
|
43 |
+
*.so
|
44 |
+
|
45 |
+
# Distribution / packaging
|
46 |
+
.Python
|
47 |
+
build/
|
48 |
+
develop-eggs/
|
49 |
+
dist/
|
50 |
+
downloads/
|
51 |
+
eggs/
|
52 |
+
.eggs/
|
53 |
+
lib64/
|
54 |
+
parts/
|
55 |
+
sdist/
|
56 |
+
var/
|
57 |
+
wheels/
|
58 |
+
pip-wheel-metadata/
|
59 |
+
share/python-wheels/
|
60 |
+
*.egg-info/
|
61 |
+
.installed.cfg
|
62 |
+
*.egg
|
63 |
+
MANIFEST
|
64 |
+
|
65 |
+
# PyInstaller
|
66 |
+
# Usually these files are written by a python script from a template
|
67 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
68 |
+
*.manifest
|
69 |
+
*.spec
|
70 |
+
|
71 |
+
# Installer training_logs
|
72 |
+
pip-log.txt
|
73 |
+
pip-delete-this-directory.txt
|
74 |
+
|
75 |
+
# Unit test / coverage reports
|
76 |
+
htmlcov/
|
77 |
+
.tox/
|
78 |
+
.nox/
|
79 |
+
.coverage
|
80 |
+
.coverage.*
|
81 |
+
.cache
|
82 |
+
nosetests.xml
|
83 |
+
coverage.xml
|
84 |
+
*.cover
|
85 |
+
*.py,cover
|
86 |
+
.hypothesis/
|
87 |
+
.pytest_cache/
|
88 |
+
|
89 |
+
# Translations
|
90 |
+
*.mo
|
91 |
+
*.pot
|
92 |
+
|
93 |
+
# Django stuff:
|
94 |
+
*.log
|
95 |
+
local_settings.py
|
96 |
+
db.sqlite3
|
97 |
+
db.sqlite3-journal
|
98 |
+
|
99 |
+
# Flask stuff:
|
100 |
+
instance/
|
101 |
+
.webassets-cache
|
102 |
+
|
103 |
+
# Scrapy stuff:
|
104 |
+
.scrapy
|
105 |
+
|
106 |
+
# Sphinx documentation
|
107 |
+
docs/_build/
|
108 |
+
|
109 |
+
# PyBuilder
|
110 |
+
target/
|
111 |
+
|
112 |
+
# Jupyter Notebook
|
113 |
+
.ipynb_checkpoints
|
114 |
+
|
115 |
+
# IPython
|
116 |
+
profile_default/
|
117 |
+
ipython_config.py
|
118 |
+
|
119 |
+
# pyenv
|
120 |
+
.python-version
|
121 |
+
|
122 |
+
# pipenv
|
123 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
124 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
125 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
126 |
+
# install all needed dependencies.
|
127 |
+
#Pipfile.lock
|
128 |
+
|
129 |
+
# celery beat schedule file
|
130 |
+
celerybeat-schedule
|
131 |
+
|
132 |
+
# SageMath parsed files
|
133 |
+
*.sage.py
|
134 |
+
|
135 |
+
# Environments
|
136 |
+
.env
|
137 |
+
.venv
|
138 |
+
env/
|
139 |
+
venv/
|
140 |
+
ENV/
|
141 |
+
env.bak/
|
142 |
+
venv.bak/
|
143 |
+
|
144 |
+
# Spyder project settings
|
145 |
+
.spyderproject
|
146 |
+
.spyproject
|
147 |
+
|
148 |
+
# Rope project settings
|
149 |
+
.ropeproject
|
150 |
+
|
151 |
+
# mkdocs documentation
|
152 |
+
/site
|
153 |
+
|
154 |
+
# mypy
|
155 |
+
.mypy_cache/
|
156 |
+
.dmypy.json
|
157 |
+
dmypy.json
|
158 |
+
|
159 |
+
# Pyre type checker
|
160 |
+
.pyre/
|
161 |
+
.DS_Store
|
162 |
+
examples/.DS_Store
|
README.md
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Super Resolution Anime Diffusion
|
3 |
+
emoji: 📊
|
4 |
+
colorFrom: yellow
|
5 |
+
colorTo: green
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.12.0
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: mit
|
11 |
+
duplicated_from: YeOldHermit/Super-Resolution-Anime-Diffusion
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
15 |
+
|
16 |
+
# Super Resolution Anime Diffusion
|
17 |
+
This is demo forked from https://huggingface.co/Linaqruf/anything-v3.0.
|
18 |
+
|
19 |
+
## Super Resolution Anime Diffusion
|
20 |
+
At this moment, many diffusion models can only generate <1024 width and length pictures.
|
21 |
+
I integrated the Super Resolution with [Anything diffusion model](https://huggingface.co/Linaqruf/anything-v3.0) to produce high resolution pictures.
|
22 |
+
Thanks to the open-source project: https://github.com/yu45020/Waifu2x
|
23 |
+
|
24 |
+
## Modifications
|
25 |
+
1. Disable the safety checker to save time and memory. You need to abide the original rules of the model.
|
26 |
+
2. Add the Super Resolution function to the model.
|
27 |
+
3. Add batch generation function to the model (see inference.py).
|
28 |
+
4.
|
29 |
+
# Origin README
|
30 |
+
---
|
31 |
+
language:
|
32 |
+
- en
|
33 |
+
license: creativeml-openrail-m
|
34 |
+
tags:
|
35 |
+
- stable-diffusion
|
36 |
+
- stable-diffusion-diffusers
|
37 |
+
- text-to-image
|
38 |
+
- diffusers
|
39 |
+
inference: true
|
40 |
+
---
|
41 |
+
|
42 |
+
# Anything V3
|
43 |
+
|
44 |
+
Welcome to Anything V3 - a latent diffusion model for weebs. This model is intended to produce high-quality, highly detailed anime style with just a few prompts. Like other anime-style Stable Diffusion models, it also supports danbooru tags to generate images.
|
45 |
+
|
46 |
+
e.g. **_1girl, white hair, golden eyes, beautiful eyes, detail, flower meadow, cumulonimbus clouds, lighting, detailed sky, garden_**
|
47 |
+
|
48 |
+
## Gradio
|
49 |
+
|
50 |
+
We support a [Gradio](https://github.com/gradio-app/gradio) Web UI to run Anything-V3.0:
|
51 |
+
|
52 |
+
[Open in Spaces](https://huggingface.co/spaces/akhaliq/anything-v3.0)
|
53 |
+
|
54 |
+
|
55 |
+
|
56 |
+
## 🧨 Diffusers
|
57 |
+
|
58 |
+
This model can be used just like any other Stable Diffusion model. For more information,
|
59 |
+
please have a look at the [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion).
|
60 |
+
|
61 |
+
You can also export the model to [ONNX](https://huggingface.co/docs/diffusers/optimization/onnx), [MPS](https://huggingface.co/docs/diffusers/optimization/mps) and/or [FLAX/JAX]().
|
62 |
+
|
63 |
+
```python
|
64 |
+
from diffusers import StableDiffusionPipeline
|
65 |
+
import torch
|
66 |
+
|
67 |
+
model_id = "Linaqruf/anything-v3.0"
|
68 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
69 |
+
pipe = pipe.to("cuda")
|
70 |
+
|
71 |
+
prompt = "pikachu"
|
72 |
+
image = pipe(prompt).images[0]
|
73 |
+
|
74 |
+
image.save("./pikachu.png")
|
75 |
+
```
|
76 |
+
|
77 |
+
## Examples
|
78 |
+
|
79 |
+
Below are some examples of images generated using this model:
|
80 |
+
|
81 |
+
**Anime Girl:**
|
82 |
+
![Anime Girl](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/1girl.png)
|
83 |
+
```
|
84 |
+
1girl, brown hair, green eyes, colorful, autumn, cumulonimbus clouds, lighting, blue sky, falling leaves, garden
|
85 |
+
Steps: 50, Sampler: DDIM, CFG scale: 12
|
86 |
+
```
|
87 |
+
**Anime Boy:**
|
88 |
+
![Anime Boy](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/1boy.png)
|
89 |
+
```
|
90 |
+
1boy, medium hair, blonde hair, blue eyes, bishounen, colorful, autumn, cumulonimbus clouds, lighting, blue sky, falling leaves, garden
|
91 |
+
Steps: 50, Sampler: DDIM, CFG scale: 12
|
92 |
+
```
|
93 |
+
**Scenery:**
|
94 |
+
![Scenery](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/scenery.png)
|
95 |
+
```
|
96 |
+
scenery, shibuya tokyo, post-apocalypse, ruins, rust, sky, skyscraper, abandoned, blue sky, broken window, building, cloud, crane machine, outdoors, overgrown, pillar, sunset
|
97 |
+
Steps: 50, Sampler: DDIM, CFG scale: 12
|
98 |
+
```
|
99 |
+
|
100 |
+
## License
|
101 |
+
|
102 |
+
This model is open access and available to all, with a CreativeML OpenRAIL-M license further specifying rights and usage.
|
103 |
+
The CreativeML OpenRAIL License specifies:
|
104 |
+
|
105 |
+
1. You can't use the model to deliberately produce nor share illegal or harmful outputs or content
|
106 |
+
2. The authors claims no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in the license
|
107 |
+
3. You may re-distribute the weights and use the model commercially and/or as a service. If you do, please be aware you have to include the same use restrictions as the ones in the license and share a copy of the CreativeML OpenRAIL-M to all your users (please read the license entirely and carefully)
|
108 |
+
[Please read the full license here](https://huggingface.co/spaces/CompVis/stable-diffusion-license)
|
README_HG.md
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Anything V3.0
|
3 |
+
emoji: 🏃
|
4 |
+
colorFrom: gray
|
5 |
+
colorTo: yellow
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.10.1
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
---
|
11 |
+
|
12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
Waifu2x/.gitattributes
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Readme_imgs/* linguist-documentation
|
Waifu2x/.gitignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
*.xml
|
3 |
+
*.iml
|
4 |
+
*.pyc
|
Waifu2x/Common.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import contextmanager
|
2 |
+
from math import sqrt, log
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
|
8 |
+
# import warnings
|
9 |
+
# warnings.simplefilter('ignore')
|
10 |
+
|
11 |
+
|
12 |
+
class BaseModule(nn.Module):
|
13 |
+
def __init__(self):
|
14 |
+
self.act_fn = None
|
15 |
+
super(BaseModule, self).__init__()
|
16 |
+
|
17 |
+
def selu_init_params(self):
|
18 |
+
for m in self.modules():
|
19 |
+
if isinstance(m, nn.Conv2d) and m.weight.requires_grad:
|
20 |
+
m.weight.data.normal_(0.0, 1.0 / sqrt(m.weight.numel()))
|
21 |
+
if m.bias is not None:
|
22 |
+
m.bias.data.fill_(0)
|
23 |
+
elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad:
|
24 |
+
m.weight.data.fill_(1)
|
25 |
+
m.bias.data.zero_()
|
26 |
+
|
27 |
+
elif isinstance(m, nn.Linear) and m.weight.requires_grad:
|
28 |
+
m.weight.data.normal_(0, 1.0 / sqrt(m.weight.numel()))
|
29 |
+
m.bias.data.zero_()
|
30 |
+
|
31 |
+
def initialize_weights_xavier_uniform(self):
|
32 |
+
for m in self.modules():
|
33 |
+
if isinstance(m, nn.Conv2d) and m.weight.requires_grad:
|
34 |
+
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
|
35 |
+
nn.init.xavier_uniform_(m.weight)
|
36 |
+
if m.bias is not None:
|
37 |
+
m.bias.data.zero_()
|
38 |
+
elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad:
|
39 |
+
m.weight.data.fill_(1)
|
40 |
+
m.bias.data.zero_()
|
41 |
+
|
42 |
+
def load_state_dict(self, state_dict, strict=True, self_state=False):
|
43 |
+
own_state = self_state if self_state else self.state_dict()
|
44 |
+
for name, param in state_dict.items():
|
45 |
+
if name in own_state:
|
46 |
+
try:
|
47 |
+
own_state[name].copy_(param.data)
|
48 |
+
except Exception as e:
|
49 |
+
print("Parameter {} fails to load.".format(name))
|
50 |
+
print("-----------------------------------------")
|
51 |
+
print(e)
|
52 |
+
else:
|
53 |
+
print("Parameter {} is not in the model. ".format(name))
|
54 |
+
|
55 |
+
@contextmanager
|
56 |
+
def set_activation_inplace(self):
|
57 |
+
if hasattr(self, 'act_fn') and hasattr(self.act_fn, 'inplace'):
|
58 |
+
# save memory
|
59 |
+
self.act_fn.inplace = True
|
60 |
+
yield
|
61 |
+
self.act_fn.inplace = False
|
62 |
+
else:
|
63 |
+
yield
|
64 |
+
|
65 |
+
def total_parameters(self):
|
66 |
+
total = sum([i.numel() for i in self.parameters()])
|
67 |
+
trainable = sum([i.numel() for i in self.parameters() if i.requires_grad])
|
68 |
+
print("Total parameters : {}. Trainable parameters : {}".format(total, trainable))
|
69 |
+
return total
|
70 |
+
|
71 |
+
def forward(self, *x):
|
72 |
+
raise NotImplementedError
|
73 |
+
|
74 |
+
|
75 |
+
class ResidualFixBlock(BaseModule):
|
76 |
+
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1,
|
77 |
+
groups=1, activation=nn.SELU(), conv=nn.Conv2d):
|
78 |
+
super(ResidualFixBlock, self).__init__()
|
79 |
+
self.act_fn = activation
|
80 |
+
self.m = nn.Sequential(
|
81 |
+
conv(in_channels, out_channels, kernel_size, padding=padding, dilation=dilation, groups=groups),
|
82 |
+
activation,
|
83 |
+
# conv(out_channels, out_channels, kernel_size, padding=(kernel_size - 1) // 2, dilation=1, groups=groups),
|
84 |
+
conv(in_channels, out_channels, kernel_size, padding=padding, dilation=dilation, groups=groups),
|
85 |
+
)
|
86 |
+
|
87 |
+
def forward(self, x):
|
88 |
+
out = self.m(x)
|
89 |
+
return self.act_fn(out + x)
|
90 |
+
|
91 |
+
|
92 |
+
class ConvBlock(BaseModule):
|
93 |
+
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1, groups=1,
|
94 |
+
activation=nn.SELU(), conv=nn.Conv2d):
|
95 |
+
super(ConvBlock, self).__init__()
|
96 |
+
self.m = nn.Sequential(conv(in_channels, out_channels, kernel_size, padding=padding,
|
97 |
+
dilation=dilation, groups=groups),
|
98 |
+
activation)
|
99 |
+
|
100 |
+
def forward(self, x):
|
101 |
+
return self.m(x)
|
102 |
+
|
103 |
+
|
104 |
+
class UpSampleBlock(BaseModule):
|
105 |
+
def __init__(self, channels, scale, activation, atrous_rate=1, conv=nn.Conv2d):
|
106 |
+
assert scale in [2, 4, 8], "Currently UpSampleBlock supports 2, 4, 8 scaling"
|
107 |
+
super(UpSampleBlock, self).__init__()
|
108 |
+
m = nn.Sequential(
|
109 |
+
conv(channels, 4 * channels, kernel_size=3, padding=atrous_rate, dilation=atrous_rate),
|
110 |
+
activation,
|
111 |
+
nn.PixelShuffle(2)
|
112 |
+
)
|
113 |
+
self.m = nn.Sequential(*[m for _ in range(int(log(scale, 2)))])
|
114 |
+
|
115 |
+
def forward(self, x):
|
116 |
+
return self.m(x)
|
117 |
+
|
118 |
+
|
119 |
+
class SpatialChannelSqueezeExcitation(BaseModule):
|
120 |
+
# https://arxiv.org/abs/1709.01507
|
121 |
+
# https://arxiv.org/pdf/1803.02579v1.pdf
|
122 |
+
def __init__(self, in_channel, reduction=16, activation=nn.ReLU()):
|
123 |
+
super(SpatialChannelSqueezeExcitation, self).__init__()
|
124 |
+
linear_nodes = max(in_channel // reduction, 4) # avoid only 1 node case
|
125 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
126 |
+
self.channel_excite = nn.Sequential(
|
127 |
+
# check the paper for the number 16 in reduction. It is selected by experiment.
|
128 |
+
nn.Linear(in_channel, linear_nodes),
|
129 |
+
activation,
|
130 |
+
nn.Linear(linear_nodes, in_channel),
|
131 |
+
nn.Sigmoid()
|
132 |
+
)
|
133 |
+
self.spatial_excite = nn.Sequential(
|
134 |
+
nn.Conv2d(in_channel, 1, kernel_size=1, stride=1, padding=0, bias=False),
|
135 |
+
nn.Sigmoid()
|
136 |
+
)
|
137 |
+
|
138 |
+
def forward(self, x):
|
139 |
+
b, c, h, w = x.size()
|
140 |
+
#
|
141 |
+
channel = self.avg_pool(x).view(b, c)
|
142 |
+
# channel = F.avg_pool2d(x, kernel_size=(h,w)).view(b,c) # used for porting to other frameworks
|
143 |
+
cSE = self.channel_excite(channel).view(b, c, 1, 1)
|
144 |
+
x_cSE = torch.mul(x, cSE)
|
145 |
+
|
146 |
+
# spatial
|
147 |
+
sSE = self.spatial_excite(x)
|
148 |
+
x_sSE = torch.mul(x, sSE)
|
149 |
+
# return x_sSE
|
150 |
+
return torch.add(x_cSE, x_sSE)
|
151 |
+
|
152 |
+
|
153 |
+
class PartialConv(nn.Module):
|
154 |
+
# reference:
|
155 |
+
# Image Inpainting for Irregular Holes Using Partial Convolutions
|
156 |
+
# http://masc.cs.gmu.edu/wiki/partialconv/show?time=2018-05-24+21%3A41%3A10
|
157 |
+
# https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py
|
158 |
+
# https://github.com/SeitaroShinagawa/chainer-partial_convolution_image_inpainting/blob/master/common/net.py
|
159 |
+
# partial based padding
|
160 |
+
# https: // github.com / NVIDIA / partialconv / blob / master / models / pd_resnet.py
|
161 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
162 |
+
padding=0, dilation=1, groups=1, bias=True):
|
163 |
+
|
164 |
+
super(PartialConv, self).__init__()
|
165 |
+
self.feature_conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride,
|
166 |
+
padding, dilation, groups, bias)
|
167 |
+
|
168 |
+
self.mask_conv = nn.Conv2d(1, 1, kernel_size, stride,
|
169 |
+
padding, dilation, groups, bias=False)
|
170 |
+
self.window_size = self.mask_conv.kernel_size[0] * self.mask_conv.kernel_size[1]
|
171 |
+
torch.nn.init.constant_(self.mask_conv.weight, 1.0)
|
172 |
+
|
173 |
+
for param in self.mask_conv.parameters():
|
174 |
+
param.requires_grad = False
|
175 |
+
|
176 |
+
def forward(self, x):
|
177 |
+
output = self.feature_conv(x)
|
178 |
+
if self.feature_conv.bias is not None:
|
179 |
+
output_bias = self.feature_conv.bias.view(1, -1, 1, 1).expand_as(output)
|
180 |
+
else:
|
181 |
+
output_bias = torch.zeros_like(output, device=x.device)
|
182 |
+
|
183 |
+
with torch.no_grad():
|
184 |
+
ones = torch.ones(1, 1, x.size(2), x.size(3), device=x.device)
|
185 |
+
output_mask = self.mask_conv(ones)
|
186 |
+
output_mask = self.window_size / output_mask
|
187 |
+
output = (output - output_bias) * output_mask + output_bias
|
188 |
+
|
189 |
+
return output
|
Waifu2x/Dataloader.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import io
|
3 |
+
import numpy as np
|
4 |
+
import re
|
5 |
+
import os
|
6 |
+
import random
|
7 |
+
from io import BytesIO
|
8 |
+
from uuid import uuid4
|
9 |
+
import sqlite3
|
10 |
+
import h5py
|
11 |
+
import torch
|
12 |
+
from PIL import Image
|
13 |
+
from torch.utils.data import Dataset
|
14 |
+
from torchvision.transforms import RandomCrop
|
15 |
+
from torchvision.transforms.functional import to_tensor
|
16 |
+
|
17 |
+
|
18 |
+
class ImageH5Data(Dataset):
|
19 |
+
def __init__(self, h5py_file, folder_name):
|
20 |
+
self.data = h5py.File(h5py_file, 'r')[folder_name]
|
21 |
+
self.data_hr = self.data['train_hr']
|
22 |
+
self.data_lr = self.data['train_lr']
|
23 |
+
self.len_imgs = len(self.data_hr)
|
24 |
+
self.h5py_file = h5py_file
|
25 |
+
self.folder_name = folder_name
|
26 |
+
|
27 |
+
def __len__(self):
|
28 |
+
# with h5py.File(self.h5py_file, 'r') as f:
|
29 |
+
# return len(f[self.folder_name]['train_lr'])
|
30 |
+
return self.len_imgs
|
31 |
+
|
32 |
+
def __getitem__(self, index):
|
33 |
+
# with h5py.File(self.h5py_file, 'r') as f:
|
34 |
+
# data_lr = f[self.folder_name]['train_lr'][index]
|
35 |
+
# data_hr = f[self.folder_name]['train_lr'][index]
|
36 |
+
#
|
37 |
+
# return data_lr, data_hr
|
38 |
+
return self.data_lr[index], self.data_hr[index]
|
39 |
+
|
40 |
+
|
41 |
+
class ImageData(Dataset):
|
42 |
+
def __init__(self,
|
43 |
+
img_folder,
|
44 |
+
patch_size=96,
|
45 |
+
shrink_size=2,
|
46 |
+
noise_level=1,
|
47 |
+
down_sample_method=None,
|
48 |
+
color_mod='RGB',
|
49 |
+
dummy_len=None):
|
50 |
+
|
51 |
+
self.img_folder = img_folder
|
52 |
+
all_img = glob.glob(self.img_folder + "/**", recursive=True)
|
53 |
+
self.img = list(filter(lambda x: x.endswith('png') or x.endswith("jpg") or x.endswith("jpeg"), all_img))
|
54 |
+
self.total_img = len(self.img)
|
55 |
+
self.dummy_len = dummy_len if dummy_len is not None else self.total_img
|
56 |
+
self.random_cropper = RandomCrop(size=patch_size)
|
57 |
+
self.color_mod = color_mod
|
58 |
+
self.img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method)
|
59 |
+
|
60 |
+
def get_img_patches(self, img_file):
|
61 |
+
img_pil = Image.open(img_file).convert("RGB")
|
62 |
+
img_patch = self.random_cropper(img_pil)
|
63 |
+
lr_hr_patches = self.img_augmenter.process(img_patch)
|
64 |
+
return lr_hr_patches
|
65 |
+
|
66 |
+
def __len__(self):
|
67 |
+
return self.dummy_len # len(self.img)
|
68 |
+
|
69 |
+
def __getitem__(self, index):
|
70 |
+
idx = random.choice(range(0, self.total_img))
|
71 |
+
img = self.img[idx]
|
72 |
+
patch = self.get_img_patches(img)
|
73 |
+
if self.color_mod == 'RGB':
|
74 |
+
lr_img = patch[0].convert("RGB")
|
75 |
+
hr_img = patch[1].convert("RGB")
|
76 |
+
elif self.color_mod == 'YCbCr':
|
77 |
+
lr_img, _, _ = patch[0].convert('YCbCr').split()
|
78 |
+
hr_img, _, _ = patch[1].convert('YCbCr').split()
|
79 |
+
else:
|
80 |
+
raise KeyError('Either RGB or YCbCr')
|
81 |
+
return to_tensor(lr_img), to_tensor(hr_img)
|
82 |
+
|
83 |
+
|
84 |
+
class Image2Sqlite(ImageData):
|
85 |
+
def __getitem__(self, item):
|
86 |
+
img = self.img[item]
|
87 |
+
lr_hr_patch = self.get_img_patches(img)
|
88 |
+
if self.color_mod == 'RGB':
|
89 |
+
lr_img = lr_hr_patch[0].convert("RGB")
|
90 |
+
hr_img = lr_hr_patch[1].convert("RGB")
|
91 |
+
elif self.color_mod == 'YCbCr':
|
92 |
+
lr_img, _, _ = lr_hr_patch[0].convert('YCbCr').split()
|
93 |
+
hr_img, _, _ = lr_hr_patch[1].convert('YCbCr').split()
|
94 |
+
else:
|
95 |
+
raise KeyError('Either RGB or YCbCr')
|
96 |
+
lr_byte = self.convert_to_bytevalue(lr_img)
|
97 |
+
hr_byte = self.convert_to_bytevalue(hr_img)
|
98 |
+
return [lr_byte, hr_byte]
|
99 |
+
|
100 |
+
@staticmethod
|
101 |
+
def convert_to_bytevalue(pil_img):
|
102 |
+
img_byte = io.BytesIO()
|
103 |
+
pil_img.save(img_byte, format='png')
|
104 |
+
return img_byte.getvalue()
|
105 |
+
|
106 |
+
|
107 |
+
class ImageDBData(Dataset):
|
108 |
+
def __init__(self, db_file, db_table="images", lr_col="lr_img", hr_col="hr_img", max_images=None):
|
109 |
+
self.db_file = db_file
|
110 |
+
self.db_table = db_table
|
111 |
+
self.lr_col = lr_col
|
112 |
+
self.hr_col = hr_col
|
113 |
+
self.total_images = self.get_num_rows(max_images)
|
114 |
+
# self.lr_hr_images = self.get_all_images()
|
115 |
+
|
116 |
+
def __len__(self):
|
117 |
+
return self.total_images
|
118 |
+
|
119 |
+
# def get_all_images(self):
|
120 |
+
# with sqlite3.connect(self.db_file) as conn:
|
121 |
+
# cursor = conn.cursor()
|
122 |
+
# cursor.execute(f"SELECT * FROM {self.db_table} LIMIT {self.total_images}")
|
123 |
+
# return cursor.fetchall()
|
124 |
+
|
125 |
+
def get_num_rows(self, max_images):
|
126 |
+
with sqlite3.connect(self.db_file) as conn:
|
127 |
+
cursor = conn.cursor()
|
128 |
+
cursor.execute(f"SELECT MAX(ROWID) FROM {self.db_table}")
|
129 |
+
db_rows = cursor.fetchone()[0]
|
130 |
+
if max_images:
|
131 |
+
return min(max_images, db_rows)
|
132 |
+
else:
|
133 |
+
return db_rows
|
134 |
+
|
135 |
+
def __getitem__(self, item):
|
136 |
+
# lr, hr = self.lr_hr_images[item]
|
137 |
+
# lr = Image.open(io.BytesIO(lr))
|
138 |
+
# hr = Image.open(io.BytesIO(hr))
|
139 |
+
# return to_tensor(lr), to_tensor(hr)
|
140 |
+
# note sqlite rowid starts with 1
|
141 |
+
with sqlite3.connect(self.db_file) as conn:
|
142 |
+
cursor = conn.cursor()
|
143 |
+
cursor.execute(f"SELECT {self.lr_col}, {self.hr_col} FROM {self.db_table} WHERE ROWID={item + 1}")
|
144 |
+
lr, hr = cursor.fetchone()
|
145 |
+
lr = Image.open(io.BytesIO(lr)).convert("RGB")
|
146 |
+
hr = Image.open(io.BytesIO(hr)).convert("RGB")
|
147 |
+
# lr = np.array(lr) # use scale [0, 255] instead of [0,1]
|
148 |
+
# hr = np.array(hr)
|
149 |
+
return to_tensor(lr), to_tensor(hr)
|
150 |
+
|
151 |
+
|
152 |
+
class ImagePatchData(Dataset):
|
153 |
+
def __init__(self, lr_folder, hr_folder):
|
154 |
+
self.lr_folder = lr_folder
|
155 |
+
self.hr_folder = hr_folder
|
156 |
+
self.lr_imgs = glob.glob(os.path.join(lr_folder, "**"))
|
157 |
+
self.total_imgs = len(self.lr_imgs)
|
158 |
+
|
159 |
+
def __len__(self):
|
160 |
+
return self.total_imgs
|
161 |
+
|
162 |
+
def __getitem__(self, item):
|
163 |
+
lr_file = self.lr_imgs[item]
|
164 |
+
hr_path = re.sub("lr", 'hr', os.path.dirname(lr_file))
|
165 |
+
filename = os.path.basename(lr_file)
|
166 |
+
hr_file = os.path.join(hr_path, filename)
|
167 |
+
return to_tensor(Image.open(lr_file)), to_tensor(Image.open(hr_file))
|
168 |
+
|
169 |
+
|
170 |
+
class ImageAugment:
|
171 |
+
def __init__(self,
|
172 |
+
shrink_size=2,
|
173 |
+
noise_level=1,
|
174 |
+
down_sample_method=None
|
175 |
+
):
|
176 |
+
# noise_level (int): 0: no noise; 1: 75-95% quality; 2:50-75%
|
177 |
+
if noise_level == 0:
|
178 |
+
self.noise_level = [0, 0]
|
179 |
+
elif noise_level == 1:
|
180 |
+
self.noise_level = [5, 25]
|
181 |
+
elif noise_level == 2:
|
182 |
+
self.noise_level = [25, 50]
|
183 |
+
else:
|
184 |
+
raise KeyError("Noise level should be either 0, 1, 2")
|
185 |
+
self.shrink_size = shrink_size
|
186 |
+
self.down_sample_method = down_sample_method
|
187 |
+
|
188 |
+
def shrink_img(self, hr_img):
|
189 |
+
|
190 |
+
if self.down_sample_method is None:
|
191 |
+
resample_method = random.choice([Image.BILINEAR, Image.BICUBIC, Image.LANCZOS])
|
192 |
+
else:
|
193 |
+
resample_method = self.down_sample_method
|
194 |
+
img_w, img_h = tuple(map(lambda x: int(x / self.shrink_size), hr_img.size))
|
195 |
+
lr_img = hr_img.resize((img_w, img_h), resample_method)
|
196 |
+
return lr_img
|
197 |
+
|
198 |
+
def add_jpeg_noise(self, hr_img):
|
199 |
+
quality = 100 - round(random.uniform(*self.noise_level))
|
200 |
+
lr_img = BytesIO()
|
201 |
+
hr_img.save(lr_img, format='JPEG', quality=quality)
|
202 |
+
lr_img.seek(0)
|
203 |
+
lr_img = Image.open(lr_img)
|
204 |
+
return lr_img
|
205 |
+
|
206 |
+
def process(self, hr_patch_pil):
|
207 |
+
lr_patch_pil = self.shrink_img(hr_patch_pil)
|
208 |
+
if self.noise_level[1] > 0:
|
209 |
+
lr_patch_pil = self.add_jpeg_noise(lr_patch_pil)
|
210 |
+
|
211 |
+
return lr_patch_pil, hr_patch_pil
|
212 |
+
|
213 |
+
def up_sample(self, img, resample):
|
214 |
+
width, height = img.size
|
215 |
+
return img.resize((self.shrink_size * width, self.shrink_size * height), resample=resample)
|
Waifu2x/Img_to_Sqlite.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Split images into small patches and insert them into sqlite db. Reading and Inserting speeds are much better than
|
3 |
+
Ubuntu's (18.04) file system when the number of patches is larger than 20k. And it has smaller size than using h5 format
|
4 |
+
|
5 |
+
Recommend to check or filter out small size patches as their content vary little. 128x128 seems better than 64x64.
|
6 |
+
|
7 |
+
|
8 |
+
"""
|
9 |
+
import sqlite3
|
10 |
+
from torch.utils.data import DataLoader
|
11 |
+
from tqdm import trange
|
12 |
+
from Dataloader import Image2Sqlite
|
13 |
+
|
14 |
+
conn = sqlite3.connect('dataset/image_yandere.db')
|
15 |
+
cursor = conn.cursor()
|
16 |
+
|
17 |
+
with conn:
|
18 |
+
cursor.execute("PRAGMA SYNCHRONOUS = OFF")
|
19 |
+
|
20 |
+
table_name = "train_images_size_128_noise_1_rgb"
|
21 |
+
lr_col = "lr_img"
|
22 |
+
hr_col = "hr_img"
|
23 |
+
|
24 |
+
with conn:
|
25 |
+
conn.execute(f"CREATE TABLE IF NOT EXISTS {table_name} ({lr_col} BLOB, {hr_col} BLOB)")
|
26 |
+
|
27 |
+
dat = Image2Sqlite(img_folder='./dataset/yande.re_test_shrink',
|
28 |
+
patch_size=256,
|
29 |
+
shrink_size=2,
|
30 |
+
noise_level=1,
|
31 |
+
down_sample_method=None,
|
32 |
+
color_mod='RGB',
|
33 |
+
dummy_len=None)
|
34 |
+
print(f"Total images {len(dat)}")
|
35 |
+
|
36 |
+
img_dat = DataLoader(dat, num_workers=6, batch_size=6, shuffle=True)
|
37 |
+
|
38 |
+
num_batches = 20
|
39 |
+
for i in trange(num_batches):
|
40 |
+
bulk = []
|
41 |
+
for lrs, hrs in img_dat:
|
42 |
+
patches = [(lrs[i], hrs[i]) for i in range(len(lrs))]
|
43 |
+
# patches = [(lrs[i], hrs[i]) for i in range(len(lrs)) if len(lrs[i]) > 14000]
|
44 |
+
|
45 |
+
bulk.extend(patches)
|
46 |
+
|
47 |
+
bulk = [i for i in bulk if len(i[0]) > 15000] # for 128x128, 14000 is fair. Around 20% of patches are filtered out
|
48 |
+
cursor.executemany(f"INSERT INTO {table_name}({lr_col}, {hr_col}) VALUES (?,?)", bulk)
|
49 |
+
conn.commit()
|
50 |
+
|
51 |
+
cursor.execute(f"select max(rowid) from {table_name}")
|
52 |
+
print(cursor.fetchall())
|
53 |
+
conn.commit()
|
54 |
+
# +++++++++++++++++++++++++++++++++++++
|
55 |
+
# Used for Create Test Database
|
56 |
+
# -------------------------------------
|
57 |
+
|
58 |
+
# cursor.execute(f"SELECT ROWID FROM {table_name} ORDER BY LENGTH({lr_col}) DESC LIMIT 400")
|
59 |
+
# rowdis = cursor.fetchall()
|
60 |
+
# rowdis = ",".join([str(i[0]) for i in rowdis])
|
61 |
+
#
|
62 |
+
# cursor.execute(f"DELETE FROM {table_name} WHERE ROWID NOT IN ({rowdis})")
|
63 |
+
# conn.commit()
|
64 |
+
# cursor.execute("vacuum")
|
65 |
+
#
|
66 |
+
# cursor.execute("""
|
67 |
+
# CREATE TABLE IF NOT EXISTS train_images_size_128_noise_1_rgb_small AS
|
68 |
+
# SELECT *
|
69 |
+
# FROM train_images_size_128_noise_1_rgb
|
70 |
+
# WHERE length(lr_img) < 14000;
|
71 |
+
# """)
|
72 |
+
#
|
73 |
+
# cursor.execute("""
|
74 |
+
# DELETE
|
75 |
+
# FROM train_images_size_128_noise_1_rgb
|
76 |
+
# WHERE length(lr_img) < 14000;
|
77 |
+
# """)
|
78 |
+
|
79 |
+
# reset index
|
80 |
+
cursor.execute("VACUUM")
|
81 |
+
conn.commit()
|
82 |
+
|
83 |
+
# +++++++++++++++++++++++++++++++++++++
|
84 |
+
# check image size
|
85 |
+
# -------------------------------------
|
86 |
+
#
|
87 |
+
|
88 |
+
from PIL import Image
|
89 |
+
import io
|
90 |
+
|
91 |
+
cursor.execute(
|
92 |
+
f"""
|
93 |
+
select {hr_col} from {table_name}
|
94 |
+
ORDER BY LENGTH({hr_col}) desc
|
95 |
+
limit 100
|
96 |
+
"""
|
97 |
+
)
|
98 |
+
# WHERE LENGTH({lr_col}) BETWEEN 14000 AND 16000
|
99 |
+
|
100 |
+
# small = cursor.fetchall()
|
101 |
+
# print(len(small))
|
102 |
+
for idx, i in enumerate(cursor):
|
103 |
+
img = Image.open(io.BytesIO(i[0]))
|
104 |
+
img.save(f"dataset/check/{idx}.png")
|
105 |
+
|
106 |
+
# +++++++++++++++++++++++++++++++++++++
|
107 |
+
# Check Image Variance
|
108 |
+
# -------------------------------------
|
109 |
+
|
110 |
+
import pandas as pd
|
111 |
+
import matplotlib.pyplot as plt
|
112 |
+
|
113 |
+
dat = pd.read_sql(f"SELECT length({lr_col}) from {table_name}", conn)
|
114 |
+
dat.hist(bins=20)
|
115 |
+
plt.show()
|
Waifu2x/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
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 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
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 General Public License from time to time. Such new versions will
|
567 |
+
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 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 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 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 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 General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<http://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
Waifu2x/Loss.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from torch.nn.functional import _pointwise_loss
|
4 |
+
|
5 |
+
rgb_weights = [0.29891 * 3, 0.58661 * 3, 0.11448 * 3]
|
6 |
+
# RGB have different weights
|
7 |
+
# https://github.com/nagadomi/waifu2x/blob/master/train.lua#L109
|
8 |
+
use_cuda = torch.cuda.is_available()
|
9 |
+
FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
|
10 |
+
LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor
|
11 |
+
Tensor = FloatTensor
|
12 |
+
|
13 |
+
|
14 |
+
class WeightedHuberLoss(nn.SmoothL1Loss):
|
15 |
+
def __init__(self, weights=rgb_weights):
|
16 |
+
super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True)
|
17 |
+
self.weights = torch.FloatTensor(weights).view(3, 1, 1)
|
18 |
+
|
19 |
+
def forward(self, input_data, target):
|
20 |
+
diff = torch.abs(input_data - target)
|
21 |
+
z = torch.where(diff < 1, 0.5 * torch.pow(diff, 2), (diff - 0.5))
|
22 |
+
out = z * self.weights.expand_as(diff)
|
23 |
+
return out.mean()
|
24 |
+
|
25 |
+
|
26 |
+
def weighted_mse_loss(input, target, weights):
|
27 |
+
out = (input - target) ** 2
|
28 |
+
out = out * weights.expand_as(out)
|
29 |
+
loss = out.sum(0) # or sum over whatever dimensions
|
30 |
+
return loss / out.size(0)
|
31 |
+
|
32 |
+
|
33 |
+
class WeightedL1Loss(nn.SmoothL1Loss):
|
34 |
+
def __init__(self, weights=rgb_weights):
|
35 |
+
super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True)
|
36 |
+
self.weights = torch.FloatTensor(weights).view(3, 1, 1)
|
37 |
+
|
38 |
+
def forward(self, input_data, target):
|
39 |
+
return self.l1_loss(input_data, target, size_average=self.size_average,
|
40 |
+
reduce=self.reduce)
|
41 |
+
|
42 |
+
def l1_loss(self, input_data, target, size_average=True, reduce=True):
|
43 |
+
return _pointwise_loss(lambda a, b: torch.abs(a - b) * self.weights.expand_as(a),
|
44 |
+
torch._C._nn.l1_loss, input_data, target, size_average, reduce)
|
Waifu2x/Models.py
ADDED
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from collections import OrderedDict
|
3 |
+
from math import exp
|
4 |
+
|
5 |
+
from .Common import *
|
6 |
+
|
7 |
+
|
8 |
+
# +++++++++++++++++++++++++++++++++++++
|
9 |
+
# FP16 Training
|
10 |
+
# -------------------------------------
|
11 |
+
# Modified from Nvidia/Apex
|
12 |
+
# https://github.com/NVIDIA/apex/blob/master/apex/fp16_utils/fp16util.py
|
13 |
+
|
14 |
+
class tofp16(nn.Module):
|
15 |
+
def __init__(self):
|
16 |
+
super(tofp16, self).__init__()
|
17 |
+
|
18 |
+
def forward(self, input):
|
19 |
+
if input.is_cuda:
|
20 |
+
return input.half()
|
21 |
+
else: # PyTorch 1.0 doesn't support fp16 in CPU
|
22 |
+
return input.float()
|
23 |
+
|
24 |
+
|
25 |
+
def BN_convert_float(module):
|
26 |
+
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
|
27 |
+
module.float()
|
28 |
+
for child in module.children():
|
29 |
+
BN_convert_float(child)
|
30 |
+
return module
|
31 |
+
|
32 |
+
|
33 |
+
def network_to_half(network):
|
34 |
+
return nn.Sequential(tofp16(), BN_convert_float(network.half()))
|
35 |
+
|
36 |
+
|
37 |
+
# warnings.simplefilter('ignore')
|
38 |
+
|
39 |
+
# +++++++++++++++++++++++++++++++++++++
|
40 |
+
# DCSCN
|
41 |
+
# -------------------------------------
|
42 |
+
|
43 |
+
class DCSCN(BaseModule):
|
44 |
+
# https://github.com/jiny2001/dcscn-super-resolution
|
45 |
+
def __init__(self,
|
46 |
+
color_channel=3,
|
47 |
+
up_scale=2,
|
48 |
+
feature_layers=12,
|
49 |
+
first_feature_filters=196,
|
50 |
+
last_feature_filters=48,
|
51 |
+
reconstruction_filters=128,
|
52 |
+
up_sampler_filters=32
|
53 |
+
):
|
54 |
+
super(DCSCN, self).__init__()
|
55 |
+
self.total_feature_channels = 0
|
56 |
+
self.total_reconstruct_filters = 0
|
57 |
+
self.upscale = up_scale
|
58 |
+
|
59 |
+
self.act_fn = nn.SELU(inplace=False)
|
60 |
+
self.feature_block = self.make_feature_extraction_block(color_channel,
|
61 |
+
feature_layers,
|
62 |
+
first_feature_filters,
|
63 |
+
last_feature_filters)
|
64 |
+
|
65 |
+
self.reconstruction_block = self.make_reconstruction_block(reconstruction_filters)
|
66 |
+
self.up_sampler = self.make_upsampler(up_sampler_filters, color_channel)
|
67 |
+
self.selu_init_params()
|
68 |
+
|
69 |
+
def selu_init_params(self):
|
70 |
+
for i in self.modules():
|
71 |
+
if isinstance(i, nn.Conv2d):
|
72 |
+
i.weight.data.normal_(0.0, 1.0 / sqrt(i.weight.numel()))
|
73 |
+
if i.bias is not None:
|
74 |
+
i.bias.data.fill_(0)
|
75 |
+
|
76 |
+
def conv_block(self, in_channel, out_channel, kernel_size):
|
77 |
+
m = OrderedDict([
|
78 |
+
# ("Padding", nn.ReplicationPad2d((kernel_size - 1) // 2)),
|
79 |
+
('Conv2d', nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)),
|
80 |
+
('Activation', self.act_fn)
|
81 |
+
])
|
82 |
+
|
83 |
+
return nn.Sequential(m)
|
84 |
+
|
85 |
+
def make_feature_extraction_block(self, color_channel, num_layers, first_filters, last_filters):
|
86 |
+
# input layer
|
87 |
+
feature_block = [("Feature 1", self.conv_block(color_channel, first_filters, 3))]
|
88 |
+
# exponential decay
|
89 |
+
# rest layers
|
90 |
+
alpha_rate = log(first_filters / last_filters) / (num_layers - 1)
|
91 |
+
filter_nums = [round(first_filters * exp(-alpha_rate * i)) for i in range(num_layers)]
|
92 |
+
|
93 |
+
self.total_feature_channels = sum(filter_nums)
|
94 |
+
|
95 |
+
layer_filters = [[filter_nums[i], filter_nums[i + 1], 3] for i in range(num_layers - 1)]
|
96 |
+
|
97 |
+
feature_block.extend([("Feature {}".format(index + 2), self.conv_block(*x))
|
98 |
+
for index, x in enumerate(layer_filters)])
|
99 |
+
return nn.Sequential(OrderedDict(feature_block))
|
100 |
+
|
101 |
+
def make_reconstruction_block(self, num_filters):
|
102 |
+
B1 = self.conv_block(self.total_feature_channels, num_filters // 2, 1)
|
103 |
+
B2 = self.conv_block(num_filters // 2, num_filters, 3)
|
104 |
+
m = OrderedDict([
|
105 |
+
("A", self.conv_block(self.total_feature_channels, num_filters, 1)),
|
106 |
+
("B", nn.Sequential(*[B1, B2]))
|
107 |
+
])
|
108 |
+
self.total_reconstruct_filters = num_filters * 2
|
109 |
+
return nn.Sequential(m)
|
110 |
+
|
111 |
+
def make_upsampler(self, out_channel, color_channel):
|
112 |
+
out = out_channel * self.upscale ** 2
|
113 |
+
m = OrderedDict([
|
114 |
+
('Conv2d_block', self.conv_block(self.total_reconstruct_filters, out, kernel_size=3)),
|
115 |
+
('PixelShuffle', nn.PixelShuffle(self.upscale)),
|
116 |
+
("Conv2d", nn.Conv2d(out_channel, color_channel, kernel_size=3, padding=1, bias=False))
|
117 |
+
])
|
118 |
+
|
119 |
+
return nn.Sequential(m)
|
120 |
+
|
121 |
+
def forward(self, x):
|
122 |
+
# residual learning
|
123 |
+
lr, lr_up = x
|
124 |
+
feature = []
|
125 |
+
for layer in self.feature_block.children():
|
126 |
+
lr = layer(lr)
|
127 |
+
feature.append(lr)
|
128 |
+
feature = torch.cat(feature, dim=1)
|
129 |
+
|
130 |
+
reconstruction = [layer(feature) for layer in self.reconstruction_block.children()]
|
131 |
+
reconstruction = torch.cat(reconstruction, dim=1)
|
132 |
+
|
133 |
+
lr = self.up_sampler(reconstruction)
|
134 |
+
return lr + lr_up
|
135 |
+
|
136 |
+
|
137 |
+
# +++++++++++++++++++++++++++++++++++++
|
138 |
+
# CARN
|
139 |
+
# -------------------------------------
|
140 |
+
|
141 |
+
class CARN_Block(BaseModule):
|
142 |
+
def __init__(self, channels, kernel_size=3, padding=1, dilation=1,
|
143 |
+
groups=1, activation=nn.SELU(), repeat=3,
|
144 |
+
SEBlock=False, conv=nn.Conv2d,
|
145 |
+
single_conv_size=1, single_conv_group=1):
|
146 |
+
super(CARN_Block, self).__init__()
|
147 |
+
m = []
|
148 |
+
for i in range(repeat):
|
149 |
+
m.append(ResidualFixBlock(channels, channels, kernel_size=kernel_size, padding=padding, dilation=dilation,
|
150 |
+
groups=groups, activation=activation, conv=conv))
|
151 |
+
if SEBlock:
|
152 |
+
m.append(SpatialChannelSqueezeExcitation(channels, reduction=channels))
|
153 |
+
self.blocks = nn.Sequential(*m)
|
154 |
+
self.singles = nn.Sequential(
|
155 |
+
*[ConvBlock(channels * (i + 2), channels, kernel_size=single_conv_size,
|
156 |
+
padding=(single_conv_size - 1) // 2, groups=single_conv_group,
|
157 |
+
activation=activation, conv=conv)
|
158 |
+
for i in range(repeat)])
|
159 |
+
|
160 |
+
def forward(self, x):
|
161 |
+
c0 = x
|
162 |
+
for block, single in zip(self.blocks, self.singles):
|
163 |
+
b = block(x)
|
164 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
165 |
+
x = single(c)
|
166 |
+
|
167 |
+
return x
|
168 |
+
|
169 |
+
|
170 |
+
class CARN(BaseModule):
|
171 |
+
# Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network
|
172 |
+
# https://github.com/nmhkahn/CARN-pytorch
|
173 |
+
def __init__(self,
|
174 |
+
color_channels=3,
|
175 |
+
mid_channels=64,
|
176 |
+
scale=2,
|
177 |
+
activation=nn.SELU(),
|
178 |
+
num_blocks=3,
|
179 |
+
conv=nn.Conv2d):
|
180 |
+
super(CARN, self).__init__()
|
181 |
+
|
182 |
+
self.color_channels = color_channels
|
183 |
+
self.mid_channels = mid_channels
|
184 |
+
self.scale = scale
|
185 |
+
|
186 |
+
self.entry_block = ConvBlock(color_channels, mid_channels, kernel_size=3, padding=1, activation=activation,
|
187 |
+
conv=conv)
|
188 |
+
self.blocks = nn.Sequential(
|
189 |
+
*[CARN_Block(mid_channels, kernel_size=3, padding=1, activation=activation, conv=conv,
|
190 |
+
single_conv_size=1, single_conv_group=1)
|
191 |
+
for _ in range(num_blocks)])
|
192 |
+
self.singles = nn.Sequential(
|
193 |
+
*[ConvBlock(mid_channels * (i + 2), mid_channels, kernel_size=1, padding=0,
|
194 |
+
activation=activation, conv=conv)
|
195 |
+
for i in range(num_blocks)])
|
196 |
+
|
197 |
+
self.upsampler = UpSampleBlock(mid_channels, scale=scale, activation=activation, conv=conv)
|
198 |
+
self.exit_conv = conv(mid_channels, color_channels, kernel_size=3, padding=1)
|
199 |
+
|
200 |
+
def forward(self, x):
|
201 |
+
x = self.entry_block(x)
|
202 |
+
c0 = x
|
203 |
+
for block, single in zip(self.blocks, self.singles):
|
204 |
+
b = block(x)
|
205 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
206 |
+
x = single(c)
|
207 |
+
x = self.upsampler(x)
|
208 |
+
out = self.exit_conv(x)
|
209 |
+
return out
|
210 |
+
|
211 |
+
|
212 |
+
class CARN_V2(CARN):
|
213 |
+
def __init__(self, color_channels=3, mid_channels=64,
|
214 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
215 |
+
SEBlock=True, conv=nn.Conv2d,
|
216 |
+
atrous=(1, 1, 1), repeat_blocks=3,
|
217 |
+
single_conv_size=3, single_conv_group=1):
|
218 |
+
super(CARN_V2, self).__init__(color_channels=color_channels, mid_channels=mid_channels, scale=scale,
|
219 |
+
activation=activation, conv=conv)
|
220 |
+
|
221 |
+
num_blocks = len(atrous)
|
222 |
+
m = []
|
223 |
+
for i in range(num_blocks):
|
224 |
+
m.append(CARN_Block(mid_channels, kernel_size=3, padding=1, dilation=1,
|
225 |
+
activation=activation, SEBlock=SEBlock, conv=conv, repeat=repeat_blocks,
|
226 |
+
single_conv_size=single_conv_size, single_conv_group=single_conv_group))
|
227 |
+
|
228 |
+
self.blocks = nn.Sequential(*m)
|
229 |
+
|
230 |
+
self.singles = nn.Sequential(
|
231 |
+
*[ConvBlock(mid_channels * (i + 2), mid_channels, kernel_size=single_conv_size,
|
232 |
+
padding=(single_conv_size - 1) // 2, groups=single_conv_group,
|
233 |
+
activation=activation, conv=conv)
|
234 |
+
for i in range(num_blocks)])
|
235 |
+
|
236 |
+
def forward(self, x):
|
237 |
+
x = self.entry_block(x)
|
238 |
+
c0 = x
|
239 |
+
res = x
|
240 |
+
for block, single in zip(self.blocks, self.singles):
|
241 |
+
b = block(x)
|
242 |
+
c0 = c = torch.cat([c0, b], dim=1)
|
243 |
+
x = single(c)
|
244 |
+
x = x + res
|
245 |
+
x = self.upsampler(x)
|
246 |
+
out = self.exit_conv(x)
|
247 |
+
return out
|
248 |
+
|
249 |
+
|
250 |
+
# +++++++++++++++++++++++++++++++++++++
|
251 |
+
# original Waifu2x model
|
252 |
+
# -------------------------------------
|
253 |
+
|
254 |
+
|
255 |
+
class UpConv_7(BaseModule):
|
256 |
+
# https://github.com/nagadomi/waifu2x/blob/3c46906cb78895dbd5a25c3705994a1b2e873199/lib/srcnn.lua#L311
|
257 |
+
def __init__(self):
|
258 |
+
super(UpConv_7, self).__init__()
|
259 |
+
self.act_fn = nn.LeakyReLU(0.1, inplace=False)
|
260 |
+
self.offset = 7 # because of 0 padding
|
261 |
+
from torch.nn import ZeroPad2d
|
262 |
+
self.pad = ZeroPad2d(self.offset)
|
263 |
+
m = [nn.Conv2d(3, 16, 3, 1, 0),
|
264 |
+
self.act_fn,
|
265 |
+
nn.Conv2d(16, 32, 3, 1, 0),
|
266 |
+
self.act_fn,
|
267 |
+
nn.Conv2d(32, 64, 3, 1, 0),
|
268 |
+
self.act_fn,
|
269 |
+
nn.Conv2d(64, 128, 3, 1, 0),
|
270 |
+
self.act_fn,
|
271 |
+
nn.Conv2d(128, 128, 3, 1, 0),
|
272 |
+
self.act_fn,
|
273 |
+
nn.Conv2d(128, 256, 3, 1, 0),
|
274 |
+
self.act_fn,
|
275 |
+
# in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=
|
276 |
+
nn.ConvTranspose2d(256, 3, kernel_size=4, stride=2, padding=3, bias=False)
|
277 |
+
]
|
278 |
+
self.Sequential = nn.Sequential(*m)
|
279 |
+
|
280 |
+
def load_pre_train_weights(self, json_file):
|
281 |
+
with open(json_file) as f:
|
282 |
+
weights = json.load(f)
|
283 |
+
box = []
|
284 |
+
for i in weights:
|
285 |
+
box.append(i['weight'])
|
286 |
+
box.append(i['bias'])
|
287 |
+
own_state = self.state_dict()
|
288 |
+
for index, (name, param) in enumerate(own_state.items()):
|
289 |
+
own_state[name].copy_(torch.FloatTensor(box[index]))
|
290 |
+
|
291 |
+
def forward(self, x):
|
292 |
+
x = self.pad(x)
|
293 |
+
return self.Sequential.forward(x)
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
class Vgg_7(UpConv_7):
|
298 |
+
def __init__(self):
|
299 |
+
super(Vgg_7, self).__init__()
|
300 |
+
self.act_fn = nn.LeakyReLU(0.1, inplace=False)
|
301 |
+
self.offset = 7
|
302 |
+
m = [nn.Conv2d(3, 32, 3, 1, 0),
|
303 |
+
self.act_fn,
|
304 |
+
nn.Conv2d(32, 32, 3, 1, 0),
|
305 |
+
self.act_fn,
|
306 |
+
nn.Conv2d(32, 64, 3, 1, 0),
|
307 |
+
self.act_fn,
|
308 |
+
nn.Conv2d(64, 64, 3, 1, 0),
|
309 |
+
self.act_fn,
|
310 |
+
nn.Conv2d(64, 128, 3, 1, 0),
|
311 |
+
self.act_fn,
|
312 |
+
nn.Conv2d(128, 128, 3, 1, 0),
|
313 |
+
self.act_fn,
|
314 |
+
nn.Conv2d(128, 3, 3, 1, 0)
|
315 |
+
]
|
316 |
+
self.Sequential = nn.Sequential(*m)
|
Waifu2x/Readme.md
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Waifu2x
|
2 |
+
|
3 |
+
Re-implementation on the original [waifu2x](https://github.com/nagadomi/waifu2x) in PyTorch with additional super resolution models. This repo is mainly used to explore interesting super resolution models. User-friendly tools may not be available now ><.
|
4 |
+
|
5 |
+
## Dependencies
|
6 |
+
* Python 3x
|
7 |
+
* [PyTorch](https://pytorch.org/) >= 1 ( > 0.41 shall also work, but not guarantee)
|
8 |
+
* [Nvidia/Apex](https://github.com/NVIDIA/apex/) (used for mixed precision training, you may use the [python codes](https://github.com/NVIDIA/apex/tree/master/apex/fp16_utils) directly)
|
9 |
+
|
10 |
+
Optinal: Nvidia GPU. Model inference (32 fp only) can run in cpu only.
|
11 |
+
|
12 |
+
## What's New
|
13 |
+
* Add [CARN Model (Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network)](https://github.com/nmhkahn/CARN-pytorch). Model Codes are adapted from the authors's [github repo](https://github.com/nmhkahn/CARN-pytorch). I add [Spatial Channel Squeeze Excitation](https://arxiv.org/abs/1709.01507) and swap all 1x1 convolution with 3x3 standard convolutions. The model is trained in fp 16 with Nvidia's [apex](https://github.com/NVIDIA/apex). Details and plots on model variant can be found in [docs/CARN](./docs/CARN)
|
14 |
+
|
15 |
+
* Dilated Convolution seems less effective (if not make the model worse) in super resolution, though it brings some improvement in image segmentation, especially when dilated rate increases and then decreases. Further investigation is needed.
|
16 |
+
|
17 |
+
## How to Use
|
18 |
+
Compare the input image and upscaled image
|
19 |
+
```python
|
20 |
+
from utils.prepare_images import *
|
21 |
+
from Models import *
|
22 |
+
from torchvision.utils import save_image
|
23 |
+
model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
24 |
+
single_conv_size=3, single_conv_group=1,
|
25 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
26 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
27 |
+
|
28 |
+
model_cran_v2 = network_to_half(model_cran_v2)
|
29 |
+
checkpoint = "model_check_points/CRAN_V2/CARN_model_checkpoint.pt"
|
30 |
+
model_cran_v2.load_state_dict(torch.load(checkpoint, 'cpu'))
|
31 |
+
# if use GPU, then comment out the next line so it can use fp16.
|
32 |
+
model_cran_v2 = model_cran_v2.float()
|
33 |
+
|
34 |
+
demo_img = "input_image.png"
|
35 |
+
img = Image.open(demo_img).convert("RGB")
|
36 |
+
|
37 |
+
# origin
|
38 |
+
img_t = to_tensor(img).unsqueeze(0)
|
39 |
+
|
40 |
+
# used to compare the origin
|
41 |
+
img = img.resize((img.size[0] // 2, img.size[1] // 2), Image.BICUBIC)
|
42 |
+
|
43 |
+
# overlapping split
|
44 |
+
# if input image is too large, then split it into overlapped patches
|
45 |
+
# details can be found at [here](https://github.com/nagadomi/waifu2x/issues/238)
|
46 |
+
img_splitter = ImageSplitter(seg_size=64, scale_factor=2, boarder_pad_size=3)
|
47 |
+
img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0)
|
48 |
+
with torch.no_grad():
|
49 |
+
out = [model_cran_v2(i) for i in img_patches]
|
50 |
+
img_upscale = img_splitter.merge_img_tensor(out)
|
51 |
+
|
52 |
+
final = torch.cat([img_t, img_upscale])
|
53 |
+
save_image(final, 'out.png', nrow=2)
|
54 |
+
```
|
55 |
+
|
56 |
+
## Training
|
57 |
+
|
58 |
+
If possible, fp16 training is preferred because it is much faster with minimal quality decrease.
|
59 |
+
|
60 |
+
Sample training script is available in `train.py`, but you may need to change some liens.
|
61 |
+
|
62 |
+
### Image Processing
|
63 |
+
Original images are all at least 3k x 3K. I downsample them by LANCZOS so that one side has at most 2048, then I randomly cut them into 256x256 patches as target and use 128x128 with jpeg noise as input images. All input patches have at least 14 kb, and they are stored in SQLite with BLOB format. SQlite seems to have [better performance](https://www.sqlite.org/intern-v-extern-blob.html) than file system for small objects. H5 file format may not be optimal because of its larger size.
|
64 |
+
|
65 |
+
Although convolutions can take in any sizes of images, the content of image matters. For real life images, small patches may maintain color,brightness, etc variances in small regions, but for digital drawn images, colors are added in block areas. A small patch may end up showing entirely one color, and the model has little to learn.
|
66 |
+
|
67 |
+
For example, the following two plots come from CARN and have the same settings, including initial parameters. Both training loss and ssim are lower for 64x64, but they perform worse in test time compared to 128x128.
|
68 |
+
|
69 |
+
![loss](docs/CARN/plots/128_vs_64_model_loss.png)
|
70 |
+
![ssim](docs/CARN/plots/128_vs_64_model_ssim.png)
|
71 |
+
|
72 |
+
|
73 |
+
Downsampling methods are uniformly chosen among ```[PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.LANCZOS]``` , so different patches in the same image might be down-scaled in different ways.
|
74 |
+
|
75 |
+
Image noise are from JPEG format only. They are added by re-encoding PNG images into PIL's JPEG data with various quality. Noise level 1 means quality ranges uniformly from [75, 95]; level 2 means quality ranges uniformly from [50, 75].
|
76 |
+
|
77 |
+
|
78 |
+
## Models
|
79 |
+
Models are tuned and modified with extra features.
|
80 |
+
|
81 |
+
|
82 |
+
* [DCSCN 12](https://github.com/jiny2001/dcscn-super-resolution)
|
83 |
+
|
84 |
+
* [CRAN](https://github.com/nmhkahn/CARN-pytorch)
|
85 |
+
|
86 |
+
#### From [Waifu2x](https://github.com/nagadomi/waifu2x)
|
87 |
+
* [Upconv7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L360)
|
88 |
+
|
89 |
+
* [Vgg_7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L334)
|
90 |
+
|
91 |
+
* [Cascaded Residual U-Net with SEBlock](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L514) (PyTorch codes are not available and under testing)
|
92 |
+
|
93 |
+
#### Models Comparison
|
94 |
+
Images are from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/).
|
95 |
+
|
96 |
+
The left column is the original image, and the right column is bicubic, DCSCN, CRAN_V2
|
97 |
+
|
98 |
+
![img](docs/demo_bicubic_model_comparison.png)
|
99 |
+
|
100 |
+
|
101 |
+
![img](docs/demo_true_bicubic_dcscn_upconv.png)
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
##### Scores
|
106 |
+
The list will be updated after I add more models.
|
107 |
+
|
108 |
+
Images are twitter icons (PNG) from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/). They are cropped into non-overlapping 96x96 patches and down-scaled by 2. Then images are re-encoded into JPEG format with quality from [75, 95]. Scores are PSNR and MS-SSIM.
|
109 |
+
|
110 |
+
| | Total Parameters | BICUBIC | Random* |
|
111 |
+
| :---: | :---: | :---: | :---: |
|
112 |
+
| CRAN V2| 2,149,607 | 34.0985 (0.9924) | 34.0509 (0.9922) |
|
113 |
+
| DCSCN 12 |1,889,974 | 31.5358 (0.9851) | 31.1457 (0.9834) |
|
114 |
+
| Upconv 7| 552,480| 31.4566 (0.9788) | 30.9492 (0.9772) |
|
115 |
+
|
116 |
+
*uniformly select down scale methods from Image.BICUBIC, Image.BILINEAR, Image.LANCZOS.
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
#### DCSCN
|
123 |
+
[Fast and Accurate Image Super Resolution by Deep CNN with Skip Connection and Network in Network](https://github.com/jiny2001/dcscn-super-resolution#fast-and-accurate-image-super-resolution-by-deep-cnn-with-skip-connection-and-network-in-network)
|
124 |
+
|
125 |
+
DCSCN is very interesting as it has relatively quick forward computation, and both the shallow model (layerr 8) and deep model (layer 12) are quick to train. The settings are different from the paper.
|
126 |
+
|
127 |
+
* I use exponential decay to decrease the number of feature filters in each layer. [Here](https://github.com/jiny2001/dcscn-super-resolution/blob/a868775930c6b36922897b0203468f3f1481e935/DCSCN.py#L204) is the original filter decay method.
|
128 |
+
|
129 |
+
* I also increase the reconstruction filters from 48 to 128.
|
130 |
+
|
131 |
+
* All activations are replaced by SELU. Dropout and weight decay are not added neither because they significantly increase the training time.
|
132 |
+
|
133 |
+
* The loss function is changed from MSE to L1.
|
134 |
+
According to [Loss Functions for Image Restoration with Neural
|
135 |
+
Networks](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0ahUKEwi7kuGt_7_bAhXrqVQKHRqhCcUQFghUMAM&url=http%3A%2F%2Fresearch.nvidia.com%2Fsites%2Fdefault%2Ffiles%2Fpubs%2F2017-03_Loss-Functions-for%2Fcomparison_tci.pdf&usg=AOvVaw1p0ndOKRH2ZaEsumO7d_bA), L1 seems to be more robust and converges faster than MSE. But the authors find the results from L1 and MSE are [similar](https://github.com/jiny2001/dcscn-super-resolution/issues/29).
|
136 |
+
|
137 |
+
|
138 |
+
I need to thank jiny2001 (one of the paper's author) to test the difference of SELU and PRELU. SELU seems more stable and has fewer parameters to train. It is a good drop in replacement
|
139 |
+
>layers=8, filters=96 and dataset=yang91+bsd200.
|
140 |
+
![](docs/DCSCN_comparison/selu_prelu.png)
|
141 |
+
The details can be found in [here]( https://github.com/jiny2001/dcscn-super-resolution/issues/29).
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
A pre-trained 12-layer model as well as model parameters are available. The model run time is around 3-5 times of Waifu2x. The output quality is usually visually indistinguishable, but its PSNR and SSIM are bit higher. Though, such comparison is not fair since the 12-layer model has around 1,889,974 parameters, 5 times more than waifu2x's Upconv_7 model.
|
146 |
+
|
147 |
+
#### CARN
|
148 |
+
Channels are set to 64 across all blocks, so residual adds are very effective. Increase the channels to 128 lower the loss curve a little bit but doubles the total parameters from 0.9 Millions to 3 Millions. 32 Channels has much worse performance. Increasing the number of cascaded blocks from 3 to 5 doesn't lower the loss a lot.
|
149 |
+
|
150 |
+
SE Blocks seems to have the most obvious improvement without increasing the computation a lot. Partial based padding seems have little effect if not decrease the quality. Atrous convolution is slower about 10%-20% than normal convolution in Pytorch 1.0, but there are no obvious improvement.
|
151 |
+
|
152 |
+
Another more effective model is to add upscaled input image to the final convolution. A simple bilinear upscaled image seems sufficient.
|
153 |
+
|
154 |
+
More examples on model configurations can be found in [docs/CARN folder](./docs/CARN/carn_plot_loss.md)
|
155 |
+
|
156 |
+
![img](docs/CARN/plots/CARN_Compare.png)
|
157 |
+
|
158 |
+
![img](docs/CARN/plots/CARN_Compare_Res_Add.png)
|
159 |
+
|
160 |
+
### Waifu2x Original Models
|
161 |
+
Models can load waifu2x's pre-trained weights. The function ```forward_checkpoint``` sets the ```nn.LeakyReLU``` to compute data inplace.
|
162 |
+
|
163 |
+
#### Upconv_7
|
164 |
+
Original waifu2x's model. PyTorch's implementation with cpu only is around 5 times longer for large images. The output images have very close PSNR and SSIM scores compared to images generated from the [caffe version](https://github.com/lltcggie/waifu2x-caffe) , thought they are not identical.
|
165 |
+
|
166 |
+
#### Vgg_7
|
167 |
+
Not tested yet, but it is ready to use.
|
Waifu2x/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: __init__.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <[email protected]>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
9 |
+
from .magnify import ImageMagnifier
|
Waifu2x/magnify.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: test.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <[email protected]>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
9 |
+
from pathlib import Path
|
10 |
+
from typing import Union
|
11 |
+
|
12 |
+
import autocuda
|
13 |
+
import findfile
|
14 |
+
from pyabsa.utils.pyabsa_utils import fprint
|
15 |
+
from torchvision import transforms
|
16 |
+
from .utils.prepare_images import *
|
17 |
+
from .Models import *
|
18 |
+
|
19 |
+
|
20 |
+
class ImageMagnifier:
|
21 |
+
|
22 |
+
def __init__(self):
|
23 |
+
self.device = autocuda.auto_cuda()
|
24 |
+
self.model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
25 |
+
single_conv_size=3, single_conv_group=1,
|
26 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
27 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
28 |
+
|
29 |
+
self.model_cran_v2 = network_to_half(self.model_cran_v2)
|
30 |
+
self.checkpoint = findfile.find_cwd_file("CARN_model_checkpoint.pt")
|
31 |
+
self.model_cran_v2.load_state_dict(torch.load(self.checkpoint, map_location='cpu'))
|
32 |
+
# if use GPU, then comment out the next line so it can use fp16.
|
33 |
+
self.model_cran_v2 = self.model_cran_v2.float().to(self.device)
|
34 |
+
self.model_cran_v2.to(self.device)
|
35 |
+
|
36 |
+
def __image_scale(self, img, scale_factor: int = 2):
|
37 |
+
img_splitter = ImageSplitter(seg_size=64, scale_factor=scale_factor, boarder_pad_size=3)
|
38 |
+
img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0)
|
39 |
+
with torch.no_grad():
|
40 |
+
if self.device != 'cpu':
|
41 |
+
with torch.cuda.amp.autocast():
|
42 |
+
out = [self.model_cran_v2(i.to(self.device)) for i in img_patches]
|
43 |
+
else:
|
44 |
+
with torch.cpu.amp.autocast():
|
45 |
+
out = [self.model_cran_v2(i) for i in img_patches]
|
46 |
+
img_upscale = img_splitter.merge_img_tensor(out)
|
47 |
+
|
48 |
+
final = torch.cat([img_upscale])
|
49 |
+
|
50 |
+
return transforms.ToPILImage()(final[0])
|
51 |
+
|
52 |
+
def magnify(self, img, scale_factor: int = 2):
|
53 |
+
fprint("scale factor reset to:", scale_factor//2*2)
|
54 |
+
_scale_factor = scale_factor
|
55 |
+
while _scale_factor // 2 > 0:
|
56 |
+
img = self.__image_scale(img, scale_factor=2)
|
57 |
+
_scale_factor = _scale_factor // 2
|
58 |
+
return img
|
59 |
+
|
60 |
+
def magnify_from_file(self, img_path: Union[str, Path], scale_factor: int = 2, save_img: bool = True):
|
61 |
+
|
62 |
+
if not os.path.exists(img_path):
|
63 |
+
raise FileNotFoundError("Path is not found.")
|
64 |
+
if os.path.isfile(img_path):
|
65 |
+
try:
|
66 |
+
img = Image.open(img_path)
|
67 |
+
img = self.magnify(img, scale_factor)
|
68 |
+
if save_img:
|
69 |
+
img.save(os.path.join(img_path))
|
70 |
+
except Exception as e:
|
71 |
+
fprint(img_path, e)
|
72 |
+
fprint(img_path, "Done.")
|
73 |
+
|
74 |
+
elif os.path.isdir(img_path):
|
75 |
+
for path in os.listdir(img_path):
|
76 |
+
try:
|
77 |
+
img = Image.open(os.path.join(img_path, path))
|
78 |
+
img = self.magnify(img, scale_factor)
|
79 |
+
if save_img:
|
80 |
+
img.save(os.path.join(img_path, path))
|
81 |
+
except Exception as e:
|
82 |
+
fprint(path, e)
|
83 |
+
continue
|
84 |
+
fprint(path, "Done.")
|
85 |
+
else:
|
86 |
+
raise TypeError("Path is not a file or directory.")
|
Waifu2x/model_check_points/CRAN_V2/CARN_adam_checkpoint.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:292f2be9ea173861e4a7f6cf580f04fe9a1fc6c78fdac6f182cbc051ea50791e
|
3 |
+
size 31734614
|
Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a0ef4fdea5b0b2a91b05b7a39fe63df3e27e1d18df477065e7f268a7feaaad2
|
3 |
+
size 4329165
|
Waifu2x/model_check_points/CRAN_V2/CARN_scheduler_last_iter.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ba2302e523d32bfeb9b542a9dc6aa5ecdb45babc793892153245d6c69ae23433
|
3 |
+
size 151
|
Waifu2x/model_check_points/CRAN_V2/CRAN_V2_02_28_2019.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b74e163d829f6f587e3fdb0b645342e494416accb1962cf0973354de5ec157ea
|
3 |
+
size 49895595
|
Waifu2x/model_check_points/CRAN_V2/ReadME.md
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Model Specifications
|
2 |
+
|
3 |
+
|
4 |
+
```python
|
5 |
+
model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
6 |
+
single_conv_size=3, single_conv_group=1,
|
7 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
8 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
9 |
+
|
10 |
+
model_cran_v2 = network_to_half(model_cran_v2)
|
11 |
+
checkpoint = "CARN_model_checkpoint.pt"
|
12 |
+
model_cran_v2.load_state_dict(torch.load(checkpoint, 'cpu'))
|
13 |
+
model_cran_v2 = model_cran_v2.float() # if use cpu
|
14 |
+
|
15 |
+
````
|
16 |
+
|
17 |
+
To use pre-trained model for training
|
18 |
+
|
19 |
+
```python
|
20 |
+
|
21 |
+
model = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
22 |
+
single_conv_size=3, single_conv_group=1,
|
23 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
24 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
25 |
+
|
26 |
+
model = network_to_half(model)
|
27 |
+
model = model.cuda()
|
28 |
+
model.load_state_dict(torch.load("CARN_model_checkpoint.pt"))
|
29 |
+
|
30 |
+
learning_rate = 1e-4
|
31 |
+
weight_decay = 1e-6
|
32 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, amsgrad=True)
|
33 |
+
optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.0, verbose=False)
|
34 |
+
optimizer.load_state_dict(torch.load("CARN_adam_checkpoint.pt"))
|
35 |
+
|
36 |
+
last_iter = torch.load("CARN_scheduler_last_iter") # -1 if start from new
|
37 |
+
scheduler = CyclicLR(optimizer.optimizer, base_lr=1e-4, max_lr=4e-4,
|
38 |
+
step_size=3 * total_batch, mode="triangular",
|
39 |
+
last_batch_iteration=last_iter)
|
40 |
+
|
41 |
+
```
|
Waifu2x/model_check_points/CRAN_V2/test_loss.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:93f644a6a3f6636035980855f56ef3dbc8784679371b06b81e0e4d06067c142d
|
3 |
+
size 43507
|
Waifu2x/model_check_points/CRAN_V2/test_psnr.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ae8f8d1a3d175e76dcbcdcf0cede898e8f2cf169f3eec14eeb75a4e19d8e2d6b
|
3 |
+
size 42563
|
Waifu2x/model_check_points/CRAN_V2/test_ssim.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:763ff936f536b12b37b351c09f3c1290fb2188399aea3d9ce3cf069bd0d135e7
|
3 |
+
size 43515
|
Waifu2x/model_check_points/CRAN_V2/train_loss.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:85a86e94cd689adff04c4b22bf2534d17aa52af5e7309a82bc2a4f5c6c144900
|
3 |
+
size 15564175
|
Waifu2x/model_check_points/CRAN_V2/train_psnr.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2d1e88646b74a054ddf20ba41368a01162e35d9c88ac72f392a6ba08a5c7ef3b
|
3 |
+
size 15564175
|
Waifu2x/model_check_points/CRAN_V2/train_ssim.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b8da8bc73f64997c5b2d15d6161b11dbd172258a62c88572c032feb73bd022b
|
3 |
+
size 15564175
|
Waifu2x/train.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from torch import optim
|
3 |
+
from torch.utils.data import DataLoader
|
4 |
+
from torchvision.utils import save_image
|
5 |
+
from tqdm import trange
|
6 |
+
|
7 |
+
from Dataloader import *
|
8 |
+
from .utils import image_quality
|
9 |
+
from .utils.cls import CyclicLR
|
10 |
+
from .utils.prepare_images import *
|
11 |
+
|
12 |
+
train_folder = './dataset/train'
|
13 |
+
test_folder = "./dataset/test"
|
14 |
+
|
15 |
+
img_dataset = ImageDBData(db_file='dataset/images.db', db_table="train_images_size_128_noise_1_rgb", max_images=24)
|
16 |
+
img_data = DataLoader(img_dataset, batch_size=6, shuffle=True, num_workers=6)
|
17 |
+
|
18 |
+
total_batch = len(img_data)
|
19 |
+
print(len(img_dataset))
|
20 |
+
|
21 |
+
test_dataset = ImageDBData(db_file='dataset/test2.db', db_table="test_images_size_128_noise_1_rgb", max_images=None)
|
22 |
+
num_test = len(test_dataset)
|
23 |
+
test_data = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=1)
|
24 |
+
|
25 |
+
criteria = nn.L1Loss()
|
26 |
+
|
27 |
+
model = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d,
|
28 |
+
single_conv_size=3, single_conv_group=1,
|
29 |
+
scale=2, activation=nn.LeakyReLU(0.1),
|
30 |
+
SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1))
|
31 |
+
|
32 |
+
model.total_parameters()
|
33 |
+
|
34 |
+
|
35 |
+
# model.initialize_weights_xavier_uniform()
|
36 |
+
|
37 |
+
# fp16 training is available in GPU only
|
38 |
+
model = network_to_half(model)
|
39 |
+
model = model.cuda()
|
40 |
+
model.load_state_dict(torch.load("CARN_model_checkpoint.pt"))
|
41 |
+
|
42 |
+
learning_rate = 1e-4
|
43 |
+
weight_decay = 1e-6
|
44 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, amsgrad=True)
|
45 |
+
# optimizer = optim.SGD(model.parameters(), momentum=0.9, nesterov=True, weight_decay=weight_decay, lr=learning_rate)
|
46 |
+
|
47 |
+
# optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.0, verbose=False)
|
48 |
+
# optimizer.load_state_dict(torch.load("CARN_adam_checkpoint.pt"))
|
49 |
+
|
50 |
+
last_iter = -1 # torch.load("CARN_scheduler_last_iter")
|
51 |
+
scheduler = CyclicLR(optimizer, base_lr=1e-4, max_lr=1e-4,
|
52 |
+
step_size=3 * total_batch, mode="triangular",
|
53 |
+
last_batch_iteration=last_iter)
|
54 |
+
train_loss = []
|
55 |
+
train_ssim = []
|
56 |
+
train_psnr = []
|
57 |
+
|
58 |
+
test_loss = []
|
59 |
+
test_ssim = []
|
60 |
+
test_psnr = []
|
61 |
+
|
62 |
+
# train_loss = torch.load("train_loss.pt")
|
63 |
+
# train_ssim = torch.load("train_ssim.pt")
|
64 |
+
# train_psnr = torch.load("train_psnr.pt")
|
65 |
+
#
|
66 |
+
# test_loss = torch.load("test_loss.pt")
|
67 |
+
# test_ssim = torch.load("test_ssim.pt")
|
68 |
+
# test_psnr = torch.load("test_psnr.pt")
|
69 |
+
|
70 |
+
|
71 |
+
counter = 0
|
72 |
+
iteration = 2
|
73 |
+
ibar = trange(iteration, ascii=True, maxinterval=1, postfix={"avg_loss": 0, "train_ssim": 0, "test_ssim": 0})
|
74 |
+
for i in ibar:
|
75 |
+
# batch_loss = []
|
76 |
+
# insample_ssim = []
|
77 |
+
# insample_psnr = []
|
78 |
+
for index, batch in enumerate(img_data):
|
79 |
+
scheduler.batch_step()
|
80 |
+
lr_img, hr_img = batch
|
81 |
+
lr_img = lr_img.cuda().half()
|
82 |
+
hr_img = hr_img.cuda()
|
83 |
+
|
84 |
+
# model.zero_grad()
|
85 |
+
optimizer.zero_grad()
|
86 |
+
outputs = model.forward(lr_img)
|
87 |
+
outputs = outputs.float()
|
88 |
+
loss = criteria(outputs, hr_img)
|
89 |
+
# loss.backward()
|
90 |
+
optimizer.backward(loss)
|
91 |
+
# nn.utils.clip_grad_norm_(model.parameters(), 5)
|
92 |
+
optimizer.step()
|
93 |
+
|
94 |
+
counter += 1
|
95 |
+
# train_loss.append(loss.item())
|
96 |
+
|
97 |
+
ssim = image_quality.msssim(outputs, hr_img).item()
|
98 |
+
psnr = image_quality.psnr(outputs, hr_img).item()
|
99 |
+
|
100 |
+
ibar.set_postfix(ratio=index / total_batch, loss=loss.item(),
|
101 |
+
ssim=ssim, batch=index,
|
102 |
+
psnr=psnr,
|
103 |
+
lr=scheduler.current_lr
|
104 |
+
)
|
105 |
+
train_loss.append(loss.item())
|
106 |
+
train_ssim.append(ssim)
|
107 |
+
train_psnr.append(psnr)
|
108 |
+
|
109 |
+
# +++++++++++++++++++++++++++++++++++++
|
110 |
+
# save checkpoints by iterations
|
111 |
+
# -------------------------------------
|
112 |
+
|
113 |
+
if (counter + 1) % 500 == 0:
|
114 |
+
torch.save(model.state_dict(), 'CARN_model_checkpoint.pt')
|
115 |
+
torch.save(optimizer.state_dict(), 'CARN_adam_checkpoint.pt')
|
116 |
+
torch.save(train_loss, 'train_loss.pt')
|
117 |
+
torch.save(train_ssim, "train_ssim.pt")
|
118 |
+
torch.save(train_psnr, 'train_psnr.pt')
|
119 |
+
torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt")
|
120 |
+
|
121 |
+
# +++++++++++++++++++++++++++++++++++++
|
122 |
+
# End of One Epoch
|
123 |
+
# -------------------------------------
|
124 |
+
|
125 |
+
# one_ite_loss = np.mean(batch_loss)
|
126 |
+
# one_ite_ssim = np.mean(insample_ssim)
|
127 |
+
# one_ite_psnr = np.mean(insample_psnr)
|
128 |
+
|
129 |
+
# print(f"One iteration loss {one_ite_loss}, ssim {one_ite_ssim}, psnr {one_ite_psnr}")
|
130 |
+
# train_loss.append(one_ite_loss)
|
131 |
+
# train_ssim.append(one_ite_ssim)
|
132 |
+
# train_psnr.append(one_ite_psnr)
|
133 |
+
|
134 |
+
torch.save(model.state_dict(), 'CARN_model_checkpoint.pt')
|
135 |
+
# torch.save(scheduler, "CARN_scheduler_optim.pt")
|
136 |
+
torch.save(optimizer.state_dict(), 'CARN_adam_checkpoint.pt')
|
137 |
+
torch.save(train_loss, 'train_loss.pt')
|
138 |
+
torch.save(train_ssim, "train_ssim.pt")
|
139 |
+
torch.save(train_psnr, 'train_psnr.pt')
|
140 |
+
# torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt")
|
141 |
+
|
142 |
+
# +++++++++++++++++++++++++++++++++++++
|
143 |
+
# Test
|
144 |
+
# -------------------------------------
|
145 |
+
|
146 |
+
with torch.no_grad():
|
147 |
+
ssim = []
|
148 |
+
batch_loss = []
|
149 |
+
psnr = []
|
150 |
+
for index, test_batch in enumerate(test_data):
|
151 |
+
lr_img, hr_img = test_batch
|
152 |
+
lr_img = lr_img.cuda()
|
153 |
+
hr_img = hr_img.cuda()
|
154 |
+
|
155 |
+
lr_img_up = model(lr_img)
|
156 |
+
lr_img_up = lr_img_up.float()
|
157 |
+
loss = criteria(lr_img_up, hr_img)
|
158 |
+
|
159 |
+
save_image([lr_img_up[0], hr_img[0]], f"check_test_imgs/{index}.png")
|
160 |
+
batch_loss.append(loss.item())
|
161 |
+
ssim.append(image_quality.msssim(lr_img_up, hr_img).item())
|
162 |
+
psnr.append(image_quality.psnr(lr_img_up, hr_img).item())
|
163 |
+
|
164 |
+
test_ssim.append(np.mean(ssim))
|
165 |
+
test_loss.append(np.mean(batch_loss))
|
166 |
+
test_psnr.append(np.mean(psnr))
|
167 |
+
|
168 |
+
torch.save(test_loss, 'test_loss.pt')
|
169 |
+
torch.save(test_ssim, "test_ssim.pt")
|
170 |
+
torch.save(test_psnr, "test_psnr.pt")
|
171 |
+
|
172 |
+
# import subprocess
|
173 |
+
|
174 |
+
# subprocess.call(["shutdown", "/s"])
|
Waifu2x/utils/Img_to_H5.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
|
3 |
+
import h5py
|
4 |
+
from PIL import Image
|
5 |
+
from torchvision.transforms import RandomCrop
|
6 |
+
from torchvision.transforms.functional import to_tensor
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
from Dataloader import ImageAugment
|
10 |
+
|
11 |
+
patch_size = 128
|
12 |
+
shrink_size = 2
|
13 |
+
noise_level = 1
|
14 |
+
patches_per_img = 20
|
15 |
+
images = glob.glob("dataset/train/*")
|
16 |
+
|
17 |
+
database = h5py.File("train_images.hdf5", 'w')
|
18 |
+
|
19 |
+
dat_group = database.create_group("shrink_2_noise_level_1_downsample_random_rgb")
|
20 |
+
# del database['shrink_2_noise_level_1_downsample_random']
|
21 |
+
storage_lr = dat_group.create_dataset("train_lr", shape=(patches_per_img * len(images), 3,
|
22 |
+
patch_size // shrink_size,
|
23 |
+
patch_size // shrink_size),
|
24 |
+
dtype='float32',
|
25 |
+
# compression='lzf',
|
26 |
+
)
|
27 |
+
storage_hr = dat_group.create_dataset("train_hr", shape=(patches_per_img * len(images), 3,
|
28 |
+
patch_size, patch_size),
|
29 |
+
# compression='lzf',
|
30 |
+
dtype='float32')
|
31 |
+
|
32 |
+
random_cropper = RandomCrop(size=patch_size)
|
33 |
+
img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method=None)
|
34 |
+
|
35 |
+
|
36 |
+
def get_img_patches(img_pil):
|
37 |
+
img_patch = random_cropper(img_pil)
|
38 |
+
lr_hr_patches = img_augmenter.process(img_patch)
|
39 |
+
return lr_hr_patches
|
40 |
+
|
41 |
+
|
42 |
+
counter = 0
|
43 |
+
for img in tqdm(images):
|
44 |
+
img_pil = Image.open(img).convert("RGB")
|
45 |
+
for i in range(patches_per_img):
|
46 |
+
patch = get_img_patches(img_pil)
|
47 |
+
storage_lr[counter] = to_tensor(patch[0].convert("RGB")).numpy()
|
48 |
+
storage_hr[counter] = to_tensor(patch[1].convert("RGB")).numpy()
|
49 |
+
counter += 1
|
50 |
+
database.close()
|
Waifu2x/utils/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
# file: __init__.py
|
3 |
+
# time: 05/12/2022
|
4 |
+
# author: yangheng <[email protected]>
|
5 |
+
# github: https://github.com/yangheng95
|
6 |
+
# huggingface: https://huggingface.co/yangheng
|
7 |
+
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
|
8 |
+
# Copyright (C) 2021. All Rights Reserved.
|
Waifu2x/utils/cls.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This code is copied from https://github.com/thomasjpfan/pytorch/blob/401ec389db2c9d2978917a6e4d1101b20340d7e7/torch/optim/lr_scheduler.py
|
2 |
+
|
3 |
+
|
4 |
+
# This code is under review at PyTorch and is to be merged eventually to make CLR available to all.
|
5 |
+
# Tested with pytorch 0.2.0
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
|
10 |
+
class CyclicLR(object):
|
11 |
+
"""Sets the learning rate of each parameter group according to
|
12 |
+
cyclical learning rate policy (CLR). The policy cycles the learning
|
13 |
+
rate between two boundaries with a constant frequency, as detailed in
|
14 |
+
the paper `Cyclical Learning Rates for Training Neural Networks`_.
|
15 |
+
The distance between the two boundaries can be scaled on a per-iteration
|
16 |
+
or per-cycle basis.
|
17 |
+
Cyclical learning rate policy changes the learning rate after every batch.
|
18 |
+
`batch_step` should be called after a batch has been used for training.
|
19 |
+
To resume training, save `last_batch_iteration` and use it to instantiate `CycleLR`.
|
20 |
+
This class has three built-in policies, as put forth in the paper:
|
21 |
+
"triangular":
|
22 |
+
A basic triangular cycle w/ no amplitude scaling.
|
23 |
+
"triangular2":
|
24 |
+
A basic triangular cycle that scales initial amplitude by half each cycle.
|
25 |
+
"exp_range":
|
26 |
+
A cycle that scales initial amplitude by gamma**(cycle iterations) at each
|
27 |
+
cycle iteration.
|
28 |
+
This implementation was adapted from the github repo: `bckenstler/CLR`_
|
29 |
+
Args:
|
30 |
+
optimizer (Optimizer): Wrapped optimizer.
|
31 |
+
base_lr (float or list): Initial learning rate which is the
|
32 |
+
lower boundary in the cycle for eachparam groups.
|
33 |
+
Default: 0.001
|
34 |
+
max_lr (float or list): Upper boundaries in the cycle for
|
35 |
+
each parameter group. Functionally,
|
36 |
+
it defines the cycle amplitude (max_lr - base_lr).
|
37 |
+
The lr at any cycle is the sum of base_lr
|
38 |
+
and some scaling of the amplitude; therefore
|
39 |
+
max_lr may not actually be reached depending on
|
40 |
+
scaling function. Default: 0.006
|
41 |
+
step_size (int): Number of training iterations per
|
42 |
+
half cycle. Authors suggest setting step_size
|
43 |
+
2-8 x training iterations in epoch. Default: 2000
|
44 |
+
mode (str): One of {triangular, triangular2, exp_range}.
|
45 |
+
Values correspond to policies detailed above.
|
46 |
+
If scale_fn is not None, this argument is ignored.
|
47 |
+
Default: 'triangular'
|
48 |
+
gamma (float): Constant in 'exp_range' scaling function:
|
49 |
+
gamma**(cycle iterations)
|
50 |
+
Default: 1.0
|
51 |
+
scale_fn (function): Custom scaling policy defined by a single
|
52 |
+
argument lambda function, where
|
53 |
+
0 <= scale_fn(x) <= 1 for all x >= 0.
|
54 |
+
mode paramater is ignored
|
55 |
+
Default: None
|
56 |
+
scale_mode (str): {'cycle', 'iterations'}.
|
57 |
+
Defines whether scale_fn is evaluated on
|
58 |
+
cycle number or cycle iterations (training
|
59 |
+
iterations since start of cycle).
|
60 |
+
Default: 'cycle'
|
61 |
+
last_batch_iteration (int): The index of the last batch. Default: -1
|
62 |
+
Example:
|
63 |
+
>>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
|
64 |
+
>>> scheduler = torch.optim.CyclicLR(optimizer)
|
65 |
+
>>> data_loader = torch.utils.data.DataLoader(...)
|
66 |
+
>>> for epoch in range(10):
|
67 |
+
>>> for batch in data_loader:
|
68 |
+
>>> scheduler.batch_step()
|
69 |
+
>>> train_batch(...)
|
70 |
+
.. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186
|
71 |
+
.. _bckenstler/CLR: https://github.com/bckenstler/CLR
|
72 |
+
"""
|
73 |
+
|
74 |
+
def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3,
|
75 |
+
step_size=2000, mode='triangular', gamma=1.,
|
76 |
+
scale_fn=None, scale_mode='cycle', last_batch_iteration=-1):
|
77 |
+
|
78 |
+
# if not isinstance(optimizer, Optimizer):
|
79 |
+
# raise TypeError('{} is not an Optimizer'.format(
|
80 |
+
# type(optimizer).__name__))
|
81 |
+
self.optimizer = optimizer
|
82 |
+
|
83 |
+
if isinstance(base_lr, list) or isinstance(base_lr, tuple):
|
84 |
+
if len(base_lr) != len(optimizer.param_groups):
|
85 |
+
raise ValueError("expected {} base_lr, got {}".format(
|
86 |
+
len(optimizer.param_groups), len(base_lr)))
|
87 |
+
self.base_lrs = list(base_lr)
|
88 |
+
else:
|
89 |
+
self.base_lrs = [base_lr] * len(optimizer.param_groups)
|
90 |
+
|
91 |
+
if isinstance(max_lr, list) or isinstance(max_lr, tuple):
|
92 |
+
if len(max_lr) != len(optimizer.param_groups):
|
93 |
+
raise ValueError("expected {} max_lr, got {}".format(
|
94 |
+
len(optimizer.param_groups), len(max_lr)))
|
95 |
+
self.max_lrs = list(max_lr)
|
96 |
+
else:
|
97 |
+
self.max_lrs = [max_lr] * len(optimizer.param_groups)
|
98 |
+
|
99 |
+
self.step_size = step_size
|
100 |
+
|
101 |
+
if mode not in ['triangular', 'triangular2', 'exp_range'] \
|
102 |
+
and scale_fn is None:
|
103 |
+
raise ValueError('mode is invalid and scale_fn is None')
|
104 |
+
|
105 |
+
self.mode = mode
|
106 |
+
self.gamma = gamma
|
107 |
+
self.current_lr = None
|
108 |
+
|
109 |
+
if scale_fn is None:
|
110 |
+
if self.mode == 'triangular':
|
111 |
+
self.scale_fn = self._triangular_scale_fn
|
112 |
+
self.scale_mode = 'cycle'
|
113 |
+
elif self.mode == 'triangular2':
|
114 |
+
self.scale_fn = self._triangular2_scale_fn
|
115 |
+
self.scale_mode = 'cycle'
|
116 |
+
elif self.mode == 'exp_range':
|
117 |
+
self.scale_fn = self._exp_range_scale_fn
|
118 |
+
self.scale_mode = 'iterations'
|
119 |
+
else:
|
120 |
+
self.scale_fn = scale_fn
|
121 |
+
self.scale_mode = scale_mode
|
122 |
+
|
123 |
+
self.batch_step(last_batch_iteration + 1)
|
124 |
+
self.last_batch_iteration = last_batch_iteration
|
125 |
+
|
126 |
+
def batch_step(self, batch_iteration=None):
|
127 |
+
if batch_iteration is None:
|
128 |
+
batch_iteration = self.last_batch_iteration + 1
|
129 |
+
self.last_batch_iteration = batch_iteration
|
130 |
+
for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):
|
131 |
+
param_group['lr'] = lr
|
132 |
+
self.current_lr = lr
|
133 |
+
|
134 |
+
def _triangular_scale_fn(self, x):
|
135 |
+
return 1.
|
136 |
+
|
137 |
+
def _triangular2_scale_fn(self, x):
|
138 |
+
return 1 / (2. ** (x - 1))
|
139 |
+
|
140 |
+
def _exp_range_scale_fn(self, x):
|
141 |
+
return self.gamma ** (x)
|
142 |
+
|
143 |
+
def get_lr(self):
|
144 |
+
step_size = float(self.step_size)
|
145 |
+
cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size))
|
146 |
+
x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1)
|
147 |
+
|
148 |
+
lrs = []
|
149 |
+
param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs)
|
150 |
+
for param_group, base_lr, max_lr in param_lrs:
|
151 |
+
base_height = (max_lr - base_lr) * np.maximum(0, (1 - x))
|
152 |
+
if self.scale_mode == 'cycle':
|
153 |
+
lr = base_lr + base_height * self.scale_fn(cycle)
|
154 |
+
else:
|
155 |
+
lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration)
|
156 |
+
lrs.append(lr)
|
157 |
+
return lrs
|
Waifu2x/utils/image_quality.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Pytorch Multi-Scale Structural Similarity Index (SSIM)
|
2 |
+
# This code is written by jorge-pessoa (https://github.com/jorge-pessoa/pytorch-msssim)
|
3 |
+
# MIT licence
|
4 |
+
import math
|
5 |
+
from math import exp
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from torch.autograd import Variable
|
10 |
+
|
11 |
+
|
12 |
+
# +++++++++++++++++++++++++++++++++++++
|
13 |
+
# SSIM
|
14 |
+
# -------------------------------------
|
15 |
+
|
16 |
+
def gaussian(window_size, sigma):
|
17 |
+
gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
|
18 |
+
return gauss / gauss.sum()
|
19 |
+
|
20 |
+
|
21 |
+
def create_window(window_size, channel):
|
22 |
+
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
23 |
+
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
|
24 |
+
window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
|
25 |
+
return window
|
26 |
+
|
27 |
+
|
28 |
+
def _ssim(img1, img2, window, window_size, channel, size_average=True, full=False):
|
29 |
+
padd = 0
|
30 |
+
|
31 |
+
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
32 |
+
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
33 |
+
|
34 |
+
mu1_sq = mu1.pow(2)
|
35 |
+
mu2_sq = mu2.pow(2)
|
36 |
+
mu1_mu2 = mu1 * mu2
|
37 |
+
|
38 |
+
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
|
39 |
+
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
|
40 |
+
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
|
41 |
+
|
42 |
+
C1 = 0.01 ** 2
|
43 |
+
C2 = 0.03 ** 2
|
44 |
+
|
45 |
+
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
|
46 |
+
|
47 |
+
v1 = 2.0 * sigma12 + C2
|
48 |
+
v2 = sigma1_sq + sigma2_sq + C2
|
49 |
+
cs = torch.mean(v1 / v2)
|
50 |
+
|
51 |
+
if size_average:
|
52 |
+
ret = ssim_map.mean()
|
53 |
+
else:
|
54 |
+
ret = ssim_map.mean(1).mean(1).mean(1)
|
55 |
+
|
56 |
+
if full:
|
57 |
+
return ret, cs
|
58 |
+
return ret
|
59 |
+
|
60 |
+
|
61 |
+
class SSIM(torch.nn.Module):
|
62 |
+
def __init__(self, window_size=11, size_average=True):
|
63 |
+
super(SSIM, self).__init__()
|
64 |
+
self.window_size = window_size
|
65 |
+
self.size_average = size_average
|
66 |
+
self.channel = 1
|
67 |
+
self.window = create_window(window_size, self.channel)
|
68 |
+
|
69 |
+
def forward(self, img1, img2):
|
70 |
+
(_, channel, _, _) = img1.size()
|
71 |
+
|
72 |
+
if channel == self.channel and self.window.data.type() == img1.data.type():
|
73 |
+
window = self.window
|
74 |
+
else:
|
75 |
+
window = create_window(self.window_size, channel)
|
76 |
+
|
77 |
+
if img1.is_cuda:
|
78 |
+
window = window.cuda(img1.get_device())
|
79 |
+
window = window.type_as(img1)
|
80 |
+
|
81 |
+
self.window = window
|
82 |
+
self.channel = channel
|
83 |
+
|
84 |
+
return _ssim(img1, img2, window, self.window_size, channel, self.size_average)
|
85 |
+
|
86 |
+
|
87 |
+
def ssim(img1, img2, window_size=11, size_average=True, full=False):
|
88 |
+
(_, channel, height, width) = img1.size()
|
89 |
+
|
90 |
+
real_size = min(window_size, height, width)
|
91 |
+
window = create_window(real_size, channel)
|
92 |
+
|
93 |
+
if img1.is_cuda:
|
94 |
+
window = window.cuda(img1.get_device())
|
95 |
+
window = window.type_as(img1)
|
96 |
+
|
97 |
+
return _ssim(img1, img2, window, real_size, channel, size_average, full=full)
|
98 |
+
|
99 |
+
|
100 |
+
def msssim(img1, img2, window_size=11, size_average=True):
|
101 |
+
# TODO: fix NAN results
|
102 |
+
if img1.size() != img2.size():
|
103 |
+
raise RuntimeError('Input images must have the same shape (%s vs. %s).' %
|
104 |
+
(img1.size(), img2.size()))
|
105 |
+
if len(img1.size()) != 4:
|
106 |
+
raise RuntimeError('Input images must have four dimensions, not %d' %
|
107 |
+
len(img1.size()))
|
108 |
+
|
109 |
+
weights = torch.tensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=img1.dtype)
|
110 |
+
if img1.is_cuda:
|
111 |
+
weights = weights.cuda(img1.get_device())
|
112 |
+
|
113 |
+
levels = weights.size()[0]
|
114 |
+
mssim = []
|
115 |
+
mcs = []
|
116 |
+
for _ in range(levels):
|
117 |
+
sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True)
|
118 |
+
mssim.append(sim)
|
119 |
+
mcs.append(cs)
|
120 |
+
|
121 |
+
img1 = F.avg_pool2d(img1, (2, 2))
|
122 |
+
img2 = F.avg_pool2d(img2, (2, 2))
|
123 |
+
|
124 |
+
mssim = torch.stack(mssim)
|
125 |
+
mcs = torch.stack(mcs)
|
126 |
+
return (torch.prod(mcs[0:levels - 1] ** weights[0:levels - 1]) *
|
127 |
+
(mssim[levels - 1] ** weights[levels - 1]))
|
128 |
+
|
129 |
+
|
130 |
+
class MSSSIM(torch.nn.Module):
|
131 |
+
def __init__(self, window_size=11, size_average=True, channel=3):
|
132 |
+
super(MSSSIM, self).__init__()
|
133 |
+
self.window_size = window_size
|
134 |
+
self.size_average = size_average
|
135 |
+
self.channel = channel
|
136 |
+
|
137 |
+
def forward(self, img1, img2):
|
138 |
+
# TODO: store window between calls if possible
|
139 |
+
return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average)
|
140 |
+
|
141 |
+
|
142 |
+
def calc_psnr(sr, hr, scale=0, benchmark=False):
|
143 |
+
# adapt from EDSR: https://github.com/thstkdgus35/EDSR-PyTorch
|
144 |
+
diff = (sr - hr).data
|
145 |
+
if benchmark:
|
146 |
+
shave = scale
|
147 |
+
if diff.size(1) > 1:
|
148 |
+
convert = diff.new(1, 3, 1, 1)
|
149 |
+
convert[0, 0, 0, 0] = 65.738
|
150 |
+
convert[0, 1, 0, 0] = 129.057
|
151 |
+
convert[0, 2, 0, 0] = 25.064
|
152 |
+
diff.mul_(convert).div_(256)
|
153 |
+
diff = diff.sum(dim=1, keepdim=True)
|
154 |
+
else:
|
155 |
+
shave = scale + 6
|
156 |
+
|
157 |
+
valid = diff[:, :, shave:-shave, shave:-shave]
|
158 |
+
mse = valid.pow(2).mean()
|
159 |
+
|
160 |
+
return -10 * math.log10(mse)
|
161 |
+
|
162 |
+
|
163 |
+
# +++++++++++++++++++++++++++++++++++++
|
164 |
+
# PSNR
|
165 |
+
# -------------------------------------
|
166 |
+
from torch import nn
|
167 |
+
|
168 |
+
|
169 |
+
def psnr(predict, target):
|
170 |
+
with torch.no_grad():
|
171 |
+
criteria = nn.MSELoss()
|
172 |
+
mse = criteria(predict, target)
|
173 |
+
return -10 * torch.log10(mse)
|
Waifu2x/utils/prepare_images.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import glob
|
3 |
+
import os
|
4 |
+
from multiprocessing.dummy import Pool as ThreadPool
|
5 |
+
|
6 |
+
from PIL import Image
|
7 |
+
from torchvision.transforms.functional import to_tensor
|
8 |
+
|
9 |
+
from ..Models import *
|
10 |
+
|
11 |
+
|
12 |
+
class ImageSplitter:
|
13 |
+
# key points:
|
14 |
+
# Boarder padding and over-lapping img splitting to avoid the instability of edge value
|
15 |
+
# Thanks Waifu2x's autorh nagadomi for suggestions (https://github.com/nagadomi/waifu2x/issues/238)
|
16 |
+
|
17 |
+
def __init__(self, seg_size=48, scale_factor=2, boarder_pad_size=3):
|
18 |
+
self.seg_size = seg_size
|
19 |
+
self.scale_factor = scale_factor
|
20 |
+
self.pad_size = boarder_pad_size
|
21 |
+
self.height = 0
|
22 |
+
self.width = 0
|
23 |
+
self.upsampler = nn.Upsample(scale_factor=scale_factor, mode='bilinear')
|
24 |
+
|
25 |
+
def split_img_tensor(self, pil_img, scale_method=Image.BILINEAR, img_pad=0):
|
26 |
+
# resize image and convert them into tensor
|
27 |
+
img_tensor = to_tensor(pil_img).unsqueeze(0)
|
28 |
+
img_tensor = nn.ReplicationPad2d(self.pad_size)(img_tensor)
|
29 |
+
batch, channel, height, width = img_tensor.size()
|
30 |
+
self.height = height
|
31 |
+
self.width = width
|
32 |
+
|
33 |
+
if scale_method is not None:
|
34 |
+
img_up = pil_img.resize((2 * pil_img.size[0], 2 * pil_img.size[1]), scale_method)
|
35 |
+
img_up = to_tensor(img_up).unsqueeze(0)
|
36 |
+
img_up = nn.ReplicationPad2d(self.pad_size * self.scale_factor)(img_up)
|
37 |
+
|
38 |
+
patch_box = []
|
39 |
+
# avoid the residual part is smaller than the padded size
|
40 |
+
if height % self.seg_size < self.pad_size or width % self.seg_size < self.pad_size:
|
41 |
+
self.seg_size += self.scale_factor * self.pad_size
|
42 |
+
|
43 |
+
# split image into over-lapping pieces
|
44 |
+
for i in range(self.pad_size, height, self.seg_size):
|
45 |
+
for j in range(self.pad_size, width, self.seg_size):
|
46 |
+
part = img_tensor[:, :,
|
47 |
+
(i - self.pad_size):min(i + self.pad_size + self.seg_size, height),
|
48 |
+
(j - self.pad_size):min(j + self.pad_size + self.seg_size, width)]
|
49 |
+
if img_pad > 0:
|
50 |
+
part = nn.ZeroPad2d(img_pad)(part)
|
51 |
+
if scale_method is not None:
|
52 |
+
# part_up = self.upsampler(part)
|
53 |
+
part_up = img_up[:, :,
|
54 |
+
self.scale_factor * (i - self.pad_size):min(i + self.pad_size + self.seg_size,
|
55 |
+
height) * self.scale_factor,
|
56 |
+
self.scale_factor * (j - self.pad_size):min(j + self.pad_size + self.seg_size,
|
57 |
+
width) * self.scale_factor]
|
58 |
+
|
59 |
+
patch_box.append((part, part_up))
|
60 |
+
else:
|
61 |
+
patch_box.append(part)
|
62 |
+
return patch_box
|
63 |
+
|
64 |
+
def merge_img_tensor(self, list_img_tensor):
|
65 |
+
out = torch.zeros((1, 3, self.height * self.scale_factor, self.width * self.scale_factor))
|
66 |
+
img_tensors = copy.copy(list_img_tensor)
|
67 |
+
rem = self.pad_size * 2
|
68 |
+
|
69 |
+
pad_size = self.scale_factor * self.pad_size
|
70 |
+
seg_size = self.scale_factor * self.seg_size
|
71 |
+
height = self.scale_factor * self.height
|
72 |
+
width = self.scale_factor * self.width
|
73 |
+
for i in range(pad_size, height, seg_size):
|
74 |
+
for j in range(pad_size, width, seg_size):
|
75 |
+
part = img_tensors.pop(0)
|
76 |
+
part = part[:, :, rem:-rem, rem:-rem]
|
77 |
+
# might have error
|
78 |
+
if len(part.size()) > 3:
|
79 |
+
_, _, p_h, p_w = part.size()
|
80 |
+
out[:, :, i:i + p_h, j:j + p_w] = part
|
81 |
+
# out[:,:,
|
82 |
+
# self.scale_factor*i:self.scale_factor*i+p_h,
|
83 |
+
# self.scale_factor*j:self.scale_factor*j+p_w] = part
|
84 |
+
out = out[:, :, rem:-rem, rem:-rem]
|
85 |
+
return out
|
86 |
+
|
87 |
+
|
88 |
+
def load_single_image(img_file,
|
89 |
+
up_scale=False,
|
90 |
+
up_scale_factor=2,
|
91 |
+
up_scale_method=Image.BILINEAR,
|
92 |
+
zero_padding=False):
|
93 |
+
img = Image.open(img_file).convert("RGB")
|
94 |
+
out = to_tensor(img).unsqueeze(0)
|
95 |
+
if zero_padding:
|
96 |
+
out = nn.ZeroPad2d(zero_padding)(out)
|
97 |
+
if up_scale:
|
98 |
+
size = tuple(map(lambda x: x * up_scale_factor, img.size))
|
99 |
+
img_up = img.resize(size, up_scale_method)
|
100 |
+
img_up = to_tensor(img_up).unsqueeze(0)
|
101 |
+
out = (out, img_up)
|
102 |
+
|
103 |
+
return out
|
104 |
+
|
105 |
+
|
106 |
+
def standardize_img_format(img_folder):
|
107 |
+
def process(img_file):
|
108 |
+
img_path = os.path.dirname(img_file)
|
109 |
+
img_name, _ = os.path.basename(img_file).split(".")
|
110 |
+
out = os.path.join(img_path, img_name + ".JPEG")
|
111 |
+
os.rename(img_file, out)
|
112 |
+
|
113 |
+
list_imgs = []
|
114 |
+
for i in ['png', "jpeg", 'jpg']:
|
115 |
+
list_imgs.extend(glob.glob(img_folder + "**/*." + i, recursive=True))
|
116 |
+
print("Found {} images.".format(len(list_imgs)))
|
117 |
+
pool = ThreadPool(4)
|
118 |
+
pool.map(process, list_imgs)
|
119 |
+
pool.close()
|
120 |
+
pool.join()
|
app.py
ADDED
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
|
4 |
+
import autocuda
|
5 |
+
from pyabsa.utils.pyabsa_utils import fprint
|
6 |
+
|
7 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, \
|
8 |
+
DPMSolverMultistepScheduler
|
9 |
+
import gradio as gr
|
10 |
+
import torch
|
11 |
+
from PIL import Image
|
12 |
+
import utils
|
13 |
+
import datetime
|
14 |
+
import time
|
15 |
+
import psutil
|
16 |
+
from Waifu2x.magnify import ImageMagnifier
|
17 |
+
|
18 |
+
magnifier = ImageMagnifier()
|
19 |
+
|
20 |
+
start_time = time.time()
|
21 |
+
is_colab = utils.is_google_colab()
|
22 |
+
|
23 |
+
CUDA_VISIBLE_DEVICES = ''
|
24 |
+
device = autocuda.auto_cuda()
|
25 |
+
|
26 |
+
dtype = torch.float16 if device != 'cpu' else torch.float32
|
27 |
+
|
28 |
+
|
29 |
+
class Model:
|
30 |
+
def __init__(self, name, path="", prefix=""):
|
31 |
+
self.name = name
|
32 |
+
self.path = path
|
33 |
+
self.prefix = prefix
|
34 |
+
self.pipe_t2i = None
|
35 |
+
self.pipe_i2i = None
|
36 |
+
|
37 |
+
|
38 |
+
models = [
|
39 |
+
Model("anything v3", "Linaqruf/anything-v3.0", "anything v3 style"),
|
40 |
+
]
|
41 |
+
# Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "),
|
42 |
+
# Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "),
|
43 |
+
# Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "),
|
44 |
+
# Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ")
|
45 |
+
# Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""),
|
46 |
+
# Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""),
|
47 |
+
# Model("Robo Diffusion", "nousr/robo-diffusion", ""),
|
48 |
+
|
49 |
+
scheduler = DPMSolverMultistepScheduler(
|
50 |
+
beta_start=0.00085,
|
51 |
+
beta_end=0.012,
|
52 |
+
beta_schedule="scaled_linear",
|
53 |
+
num_train_timesteps=1000,
|
54 |
+
trained_betas=None,
|
55 |
+
predict_epsilon=True,
|
56 |
+
thresholding=False,
|
57 |
+
algorithm_type="dpmsolver++",
|
58 |
+
solver_type="midpoint",
|
59 |
+
lower_order_final=True,
|
60 |
+
)
|
61 |
+
|
62 |
+
custom_model = None
|
63 |
+
if is_colab:
|
64 |
+
models.insert(0, Model("Custom model"))
|
65 |
+
custom_model = models[0]
|
66 |
+
|
67 |
+
last_mode = "txt2img"
|
68 |
+
current_model = models[1] if is_colab else models[0]
|
69 |
+
current_model_path = current_model.path
|
70 |
+
|
71 |
+
if is_colab:
|
72 |
+
pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=dtype, scheduler=scheduler,
|
73 |
+
safety_checker=lambda images, clip_input: (images, False))
|
74 |
+
|
75 |
+
else: # download all models
|
76 |
+
print(f"{datetime.datetime.now()} Downloading vae...")
|
77 |
+
vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae", torch_dtype=dtype)
|
78 |
+
for model in models:
|
79 |
+
try:
|
80 |
+
print(f"{datetime.datetime.now()} Downloading {model.name} model...")
|
81 |
+
unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet", torch_dtype=dtype)
|
82 |
+
model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae,
|
83 |
+
torch_dtype=dtype, scheduler=scheduler,
|
84 |
+
safety_checker=None)
|
85 |
+
model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae,
|
86 |
+
torch_dtype=dtype,
|
87 |
+
scheduler=scheduler, safety_checker=None)
|
88 |
+
except Exception as e:
|
89 |
+
print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e))
|
90 |
+
models.remove(model)
|
91 |
+
pipe = models[0].pipe_t2i
|
92 |
+
|
93 |
+
# model.pipe_i2i = torch.compile(model.pipe_i2i)
|
94 |
+
# model.pipe_t2i = torch.compile(model.pipe_t2i)
|
95 |
+
if torch.cuda.is_available():
|
96 |
+
pipe = pipe.to(device)
|
97 |
+
|
98 |
+
|
99 |
+
# device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
|
100 |
+
|
101 |
+
|
102 |
+
def error_str(error, title="Error"):
|
103 |
+
return f"""#### {title}
|
104 |
+
{error}""" if error else ""
|
105 |
+
|
106 |
+
|
107 |
+
def custom_model_changed(path):
|
108 |
+
models[0].path = path
|
109 |
+
global current_model
|
110 |
+
current_model = models[0]
|
111 |
+
|
112 |
+
|
113 |
+
def on_model_change(model_name):
|
114 |
+
prefix = "Enter prompt. \"" + next((m.prefix for m in models if m.name == model_name),
|
115 |
+
None) + "\" is prefixed automatically" if model_name != models[
|
116 |
+
0].name else "Don't forget to use the custom model prefix in the prompt!"
|
117 |
+
|
118 |
+
return gr.update(visible=model_name == models[0].name), gr.update(placeholder=prefix)
|
119 |
+
|
120 |
+
|
121 |
+
def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5,
|
122 |
+
neg_prompt="", scale_factor=2):
|
123 |
+
fprint(psutil.virtual_memory()) # print memory usage
|
124 |
+
prompt = 'detailed fingers, beautiful hands,' + prompt
|
125 |
+
fprint(f"Prompt: {prompt}")
|
126 |
+
global current_model
|
127 |
+
for model in models:
|
128 |
+
if model.name == model_name:
|
129 |
+
current_model = model
|
130 |
+
model_path = current_model.path
|
131 |
+
|
132 |
+
generator = torch.Generator(device).manual_seed(seed) if seed != 0 else None
|
133 |
+
|
134 |
+
try:
|
135 |
+
if img is not None:
|
136 |
+
return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height,
|
137 |
+
generator, scale_factor), None
|
138 |
+
else:
|
139 |
+
return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator,
|
140 |
+
scale_factor), None
|
141 |
+
except Exception as e:
|
142 |
+
return None, error_str(e)
|
143 |
+
# if img is not None:
|
144 |
+
# return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height,
|
145 |
+
# generator, scale_factor), None
|
146 |
+
# else:
|
147 |
+
# return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator, scale_factor), None
|
148 |
+
|
149 |
+
|
150 |
+
def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator, scale_factor):
|
151 |
+
print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
|
152 |
+
|
153 |
+
global last_mode
|
154 |
+
global pipe
|
155 |
+
global current_model_path
|
156 |
+
if model_path != current_model_path or last_mode != "txt2img":
|
157 |
+
current_model_path = model_path
|
158 |
+
|
159 |
+
if is_colab or current_model == custom_model:
|
160 |
+
pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=dtype,
|
161 |
+
scheduler=scheduler,
|
162 |
+
safety_checker=lambda images, clip_input: (images, False))
|
163 |
+
else:
|
164 |
+
# pipe = pipe.to("cpu")
|
165 |
+
pipe = current_model.pipe_t2i
|
166 |
+
|
167 |
+
if torch.cuda.is_available():
|
168 |
+
pipe = pipe.to(device)
|
169 |
+
last_mode = "txt2img"
|
170 |
+
|
171 |
+
prompt = current_model.prefix + prompt
|
172 |
+
result = pipe(
|
173 |
+
prompt,
|
174 |
+
negative_prompt=neg_prompt,
|
175 |
+
# num_images_per_prompt=n_images,
|
176 |
+
num_inference_steps=int(steps),
|
177 |
+
guidance_scale=guidance,
|
178 |
+
width=width,
|
179 |
+
height=height,
|
180 |
+
generator=generator)
|
181 |
+
result.images[0] = magnifier.magnify(result.images[0], scale_factor=scale_factor)
|
182 |
+
|
183 |
+
# save image
|
184 |
+
result.images[0].save("imgs/result-{}.png".format(datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
|
185 |
+
return replace_nsfw_images(result)
|
186 |
+
|
187 |
+
|
188 |
+
def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator, scale_factor):
|
189 |
+
fprint(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
|
190 |
+
|
191 |
+
global last_mode
|
192 |
+
global pipe
|
193 |
+
global current_model_path
|
194 |
+
if model_path != current_model_path or last_mode != "img2img":
|
195 |
+
current_model_path = model_path
|
196 |
+
|
197 |
+
if is_colab or current_model == custom_model:
|
198 |
+
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=dtype,
|
199 |
+
scheduler=scheduler,
|
200 |
+
safety_checker=lambda images, clip_input: (
|
201 |
+
images, False))
|
202 |
+
else:
|
203 |
+
# pipe = pipe.to("cpu")
|
204 |
+
pipe = current_model.pipe_i2i
|
205 |
+
|
206 |
+
if torch.cuda.is_available():
|
207 |
+
pipe = pipe.to(device)
|
208 |
+
last_mode = "img2img"
|
209 |
+
|
210 |
+
prompt = current_model.prefix + prompt
|
211 |
+
ratio = min(height / img.height, width / img.width)
|
212 |
+
img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
|
213 |
+
result = pipe(
|
214 |
+
prompt,
|
215 |
+
negative_prompt=neg_prompt,
|
216 |
+
# num_images_per_prompt=n_images,
|
217 |
+
image=img,
|
218 |
+
num_inference_steps=int(steps),
|
219 |
+
strength=strength,
|
220 |
+
guidance_scale=guidance,
|
221 |
+
# width=width,
|
222 |
+
# height=height,
|
223 |
+
generator=generator)
|
224 |
+
result.images[0] = magnifier.magnify(result.images[0], scale_factor=scale_factor)
|
225 |
+
|
226 |
+
# save image
|
227 |
+
result.images[0].save("imgs/result-{}.png".format(datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
|
228 |
+
return replace_nsfw_images(result)
|
229 |
+
|
230 |
+
|
231 |
+
def replace_nsfw_images(results):
|
232 |
+
if is_colab:
|
233 |
+
return results.images[0]
|
234 |
+
if hasattr(results, "nsfw_content_detected") and results.nsfw_content_detected:
|
235 |
+
for i in range(len(results.images)):
|
236 |
+
if results.nsfw_content_detected[i]:
|
237 |
+
results.images[i] = Image.open("nsfw.png")
|
238 |
+
return results.images[0]
|
239 |
+
|
240 |
+
|
241 |
+
css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
|
242 |
+
"""
|
243 |
+
with gr.Blocks(css=css) as demo:
|
244 |
+
if not os.path.exists('imgs'):
|
245 |
+
os.mkdir('imgs')
|
246 |
+
|
247 |
+
gr.Markdown('# Super Resolution Anime Diffusion')
|
248 |
+
gr.Markdown(
|
249 |
+
"## Author: [yangheng95](https://github.com/yangheng95) Github:[Github](https://github.com/yangheng95/SuperResolutionAnimeDiffusion)")
|
250 |
+
gr.Markdown("### This demo is running on a CPU, so it will take at least 20 minutes. "
|
251 |
+
"If you have a GPU, you can clone from [Github](https://github.com/yangheng95/SuperResolutionAnimeDiffusion) and run it locally.")
|
252 |
+
gr.Markdown("### FYI: to generate a 512*512 image and magnify 4x, it only takes 5~8 seconds on a RTX 2080 GPU")
|
253 |
+
gr.Markdown(
|
254 |
+
"### You can duplicate this demo on HuggingFace Spaces, click [here](https://huggingface.co/spaces/yangheng/Super-Resolution-Anime-Diffusion?duplicate=true)")
|
255 |
+
|
256 |
+
with gr.Row():
|
257 |
+
with gr.Column(scale=55):
|
258 |
+
with gr.Group():
|
259 |
+
gr.Markdown("Text to image")
|
260 |
+
|
261 |
+
model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
|
262 |
+
|
263 |
+
with gr.Box(visible=False) as custom_model_group:
|
264 |
+
custom_model_path = gr.Textbox(label="Custom model path",
|
265 |
+
placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion",
|
266 |
+
interactive=True)
|
267 |
+
gr.HTML(
|
268 |
+
"<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
|
269 |
+
|
270 |
+
with gr.Row():
|
271 |
+
prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,
|
272 |
+
placeholder="Enter prompt. Style applied automatically").style(container=False)
|
273 |
+
with gr.Row():
|
274 |
+
generate = gr.Button(value="Generate")
|
275 |
+
|
276 |
+
with gr.Row():
|
277 |
+
with gr.Group():
|
278 |
+
neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
|
279 |
+
|
280 |
+
image_out = gr.Image(height=512)
|
281 |
+
# gallery = gr.Gallery(
|
282 |
+
# label="Generated images", show_label=False, elem_id="gallery"
|
283 |
+
# ).style(grid=[1], height="auto")
|
284 |
+
error_output = gr.Markdown()
|
285 |
+
|
286 |
+
with gr.Column(scale=45):
|
287 |
+
with gr.Group():
|
288 |
+
gr.Markdown("Image to Image")
|
289 |
+
|
290 |
+
with gr.Row():
|
291 |
+
with gr.Group():
|
292 |
+
image = gr.Image(label="Image", height=256, tool="editor", type="pil")
|
293 |
+
strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01,
|
294 |
+
value=0.5)
|
295 |
+
|
296 |
+
with gr.Row():
|
297 |
+
with gr.Group():
|
298 |
+
# n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
|
299 |
+
|
300 |
+
with gr.Row():
|
301 |
+
guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
|
302 |
+
steps = gr.Slider(label="Steps", value=15, minimum=2, maximum=75, step=1)
|
303 |
+
|
304 |
+
with gr.Row():
|
305 |
+
width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
|
306 |
+
height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
|
307 |
+
with gr.Row():
|
308 |
+
scale_factor = gr.Slider(1, 8, label='Scale factor (to magnify image) (1, 2, 4, 8)',
|
309 |
+
value=2,
|
310 |
+
step=1)
|
311 |
+
|
312 |
+
seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
|
313 |
+
|
314 |
+
if is_colab:
|
315 |
+
model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False)
|
316 |
+
custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
|
317 |
+
# n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
|
318 |
+
|
319 |
+
gr.Markdown("### based on [Anything V3](https://huggingface.co/Linaqruf/anything-v3.0)")
|
320 |
+
|
321 |
+
inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, scale_factor]
|
322 |
+
outputs = [image_out, error_output]
|
323 |
+
prompt.submit(inference, inputs=inputs, outputs=outputs)
|
324 |
+
generate.click(inference, inputs=inputs, outputs=outputs, api_name="generate")
|
325 |
+
|
326 |
+
prompt_keys = [
|
327 |
+
'girl', 'lovely', 'cute', 'beautiful eyes', 'cumulonimbus clouds', 'detailed fingers',
|
328 |
+
random.choice(['dress']),
|
329 |
+
random.choice(['white hair']),
|
330 |
+
random.choice(['blue eyes']),
|
331 |
+
random.choice(['flower meadow']),
|
332 |
+
random.choice(['Elif', 'Angel'])
|
333 |
+
]
|
334 |
+
prompt.value = ','.join(prompt_keys)
|
335 |
+
ex = gr.Examples([
|
336 |
+
[models[0].name, prompt.value, 7.5, 15],
|
337 |
+
|
338 |
+
], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False)
|
339 |
+
|
340 |
+
print(f"Space built in {time.time() - start_time:.2f} seconds")
|
341 |
+
|
342 |
+
if not is_colab:
|
343 |
+
demo.queue(concurrency_count=2)
|
344 |
+
demo.launch(debug=is_colab, enable_queue=True, share=is_colab)
|
diffusers/__init__.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .utils import (
|
2 |
+
is_flax_available,
|
3 |
+
is_inflect_available,
|
4 |
+
is_onnx_available,
|
5 |
+
is_scipy_available,
|
6 |
+
is_torch_available,
|
7 |
+
is_transformers_available,
|
8 |
+
is_unidecode_available,
|
9 |
+
)
|
10 |
+
|
11 |
+
|
12 |
+
__version__ = "0.10.0.dev0"
|
13 |
+
|
14 |
+
from .configuration_utils import ConfigMixin
|
15 |
+
from .onnx_utils import OnnxRuntimeModel
|
16 |
+
from .utils import logging
|
17 |
+
|
18 |
+
|
19 |
+
if is_torch_available():
|
20 |
+
from .modeling_utils import ModelMixin
|
21 |
+
from .models import AutoencoderKL, Transformer2DModel, UNet1DModel, UNet2DConditionModel, UNet2DModel, VQModel
|
22 |
+
from .optimization import (
|
23 |
+
get_constant_schedule,
|
24 |
+
get_constant_schedule_with_warmup,
|
25 |
+
get_cosine_schedule_with_warmup,
|
26 |
+
get_cosine_with_hard_restarts_schedule_with_warmup,
|
27 |
+
get_linear_schedule_with_warmup,
|
28 |
+
get_polynomial_decay_schedule_with_warmup,
|
29 |
+
get_scheduler,
|
30 |
+
)
|
31 |
+
from .pipeline_utils import DiffusionPipeline
|
32 |
+
from .pipelines import (
|
33 |
+
DanceDiffusionPipeline,
|
34 |
+
DDIMPipeline,
|
35 |
+
DDPMPipeline,
|
36 |
+
KarrasVePipeline,
|
37 |
+
LDMPipeline,
|
38 |
+
LDMSuperResolutionPipeline,
|
39 |
+
PNDMPipeline,
|
40 |
+
RePaintPipeline,
|
41 |
+
ScoreSdeVePipeline,
|
42 |
+
)
|
43 |
+
from .schedulers import (
|
44 |
+
DDIMScheduler,
|
45 |
+
DDPMScheduler,
|
46 |
+
DPMSolverMultistepScheduler,
|
47 |
+
EulerAncestralDiscreteScheduler,
|
48 |
+
EulerDiscreteScheduler,
|
49 |
+
HeunDiscreteScheduler,
|
50 |
+
IPNDMScheduler,
|
51 |
+
KarrasVeScheduler,
|
52 |
+
KDPM2AncestralDiscreteScheduler,
|
53 |
+
KDPM2DiscreteScheduler,
|
54 |
+
PNDMScheduler,
|
55 |
+
RePaintScheduler,
|
56 |
+
SchedulerMixin,
|
57 |
+
ScoreSdeVeScheduler,
|
58 |
+
VQDiffusionScheduler,
|
59 |
+
)
|
60 |
+
from .training_utils import EMAModel
|
61 |
+
else:
|
62 |
+
from .utils.dummy_pt_objects import * # noqa F403
|
63 |
+
|
64 |
+
if is_torch_available() and is_scipy_available():
|
65 |
+
from .schedulers import LMSDiscreteScheduler
|
66 |
+
else:
|
67 |
+
from .utils.dummy_torch_and_scipy_objects import * # noqa F403
|
68 |
+
|
69 |
+
if is_torch_available() and is_transformers_available():
|
70 |
+
from .pipelines import (
|
71 |
+
AltDiffusionImg2ImgPipeline,
|
72 |
+
AltDiffusionPipeline,
|
73 |
+
CycleDiffusionPipeline,
|
74 |
+
LDMTextToImagePipeline,
|
75 |
+
StableDiffusionImageVariationPipeline,
|
76 |
+
StableDiffusionImg2ImgPipeline,
|
77 |
+
StableDiffusionInpaintPipeline,
|
78 |
+
StableDiffusionInpaintPipelineLegacy,
|
79 |
+
StableDiffusionPipeline,
|
80 |
+
StableDiffusionPipelineSafe,
|
81 |
+
StableDiffusionUpscalePipeline,
|
82 |
+
VersatileDiffusionDualGuidedPipeline,
|
83 |
+
VersatileDiffusionImageVariationPipeline,
|
84 |
+
VersatileDiffusionPipeline,
|
85 |
+
VersatileDiffusionTextToImagePipeline,
|
86 |
+
VQDiffusionPipeline,
|
87 |
+
)
|
88 |
+
else:
|
89 |
+
from .utils.dummy_torch_and_transformers_objects import * # noqa F403
|
90 |
+
|
91 |
+
if is_torch_available() and is_transformers_available() and is_onnx_available():
|
92 |
+
from .pipelines import (
|
93 |
+
OnnxStableDiffusionImg2ImgPipeline,
|
94 |
+
OnnxStableDiffusionInpaintPipeline,
|
95 |
+
OnnxStableDiffusionInpaintPipelineLegacy,
|
96 |
+
OnnxStableDiffusionPipeline,
|
97 |
+
StableDiffusionOnnxPipeline,
|
98 |
+
)
|
99 |
+
else:
|
100 |
+
from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
|
101 |
+
|
102 |
+
if is_flax_available():
|
103 |
+
from .modeling_flax_utils import FlaxModelMixin
|
104 |
+
from .models.unet_2d_condition_flax import FlaxUNet2DConditionModel
|
105 |
+
from .models.vae_flax import FlaxAutoencoderKL
|
106 |
+
from .pipeline_flax_utils import FlaxDiffusionPipeline
|
107 |
+
from .schedulers import (
|
108 |
+
FlaxDDIMScheduler,
|
109 |
+
FlaxDDPMScheduler,
|
110 |
+
FlaxDPMSolverMultistepScheduler,
|
111 |
+
FlaxKarrasVeScheduler,
|
112 |
+
FlaxLMSDiscreteScheduler,
|
113 |
+
FlaxPNDMScheduler,
|
114 |
+
FlaxSchedulerMixin,
|
115 |
+
FlaxScoreSdeVeScheduler,
|
116 |
+
)
|
117 |
+
else:
|
118 |
+
from .utils.dummy_flax_objects import * # noqa F403
|
119 |
+
|
120 |
+
if is_flax_available() and is_transformers_available():
|
121 |
+
from .pipelines import FlaxStableDiffusionPipeline
|
122 |
+
else:
|
123 |
+
from .utils.dummy_flax_and_transformers_objects import * # noqa F403
|
diffusers/commands/__init__.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
from abc import ABC, abstractmethod
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
|
19 |
+
class BaseDiffusersCLICommand(ABC):
|
20 |
+
@staticmethod
|
21 |
+
@abstractmethod
|
22 |
+
def register_subcommand(parser: ArgumentParser):
|
23 |
+
raise NotImplementedError()
|
24 |
+
|
25 |
+
@abstractmethod
|
26 |
+
def run(self):
|
27 |
+
raise NotImplementedError()
|
diffusers/commands/diffusers_cli.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
from .env import EnvironmentCommand
|
19 |
+
|
20 |
+
|
21 |
+
def main():
|
22 |
+
parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
|
23 |
+
commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
|
24 |
+
|
25 |
+
# Register commands
|
26 |
+
EnvironmentCommand.register_subcommand(commands_parser)
|
27 |
+
|
28 |
+
# Let's go
|
29 |
+
args = parser.parse_args()
|
30 |
+
|
31 |
+
if not hasattr(args, "func"):
|
32 |
+
parser.print_help()
|
33 |
+
exit(1)
|
34 |
+
|
35 |
+
# Run
|
36 |
+
service = args.func(args)
|
37 |
+
service.run()
|
38 |
+
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
main()
|
diffusers/commands/env.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import platform
|
16 |
+
from argparse import ArgumentParser
|
17 |
+
|
18 |
+
import huggingface_hub
|
19 |
+
|
20 |
+
from .. import __version__ as version
|
21 |
+
from ..utils import is_torch_available, is_transformers_available
|
22 |
+
from . import BaseDiffusersCLICommand
|
23 |
+
|
24 |
+
|
25 |
+
def info_command_factory(_):
|
26 |
+
return EnvironmentCommand()
|
27 |
+
|
28 |
+
|
29 |
+
class EnvironmentCommand(BaseDiffusersCLICommand):
|
30 |
+
@staticmethod
|
31 |
+
def register_subcommand(parser: ArgumentParser):
|
32 |
+
download_parser = parser.add_parser("env")
|
33 |
+
download_parser.set_defaults(func=info_command_factory)
|
34 |
+
|
35 |
+
def run(self):
|
36 |
+
hub_version = huggingface_hub.__version__
|
37 |
+
|
38 |
+
pt_version = "not installed"
|
39 |
+
pt_cuda_available = "NA"
|
40 |
+
if is_torch_available():
|
41 |
+
import torch
|
42 |
+
|
43 |
+
pt_version = torch.__version__
|
44 |
+
pt_cuda_available = torch.cuda.is_available()
|
45 |
+
|
46 |
+
transformers_version = "not installed"
|
47 |
+
if is_transformers_available:
|
48 |
+
import transformers
|
49 |
+
|
50 |
+
transformers_version = transformers.__version__
|
51 |
+
|
52 |
+
info = {
|
53 |
+
"`diffusers` version": version,
|
54 |
+
"Platform": platform.platform(),
|
55 |
+
"Python version": platform.python_version(),
|
56 |
+
"PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
|
57 |
+
"Huggingface_hub version": hub_version,
|
58 |
+
"Transformers version": transformers_version,
|
59 |
+
"Using GPU in script?": "<fill in>",
|
60 |
+
"Using distributed or parallel set-up in script?": "<fill in>",
|
61 |
+
}
|
62 |
+
|
63 |
+
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
|
64 |
+
print(self.format_dict(info))
|
65 |
+
|
66 |
+
return info
|
67 |
+
|
68 |
+
@staticmethod
|
69 |
+
def format_dict(d):
|
70 |
+
return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
|
diffusers/configuration_utils.py
ADDED
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
""" ConfigMixin base class and utilities."""
|
17 |
+
import dataclasses
|
18 |
+
import functools
|
19 |
+
import importlib
|
20 |
+
import inspect
|
21 |
+
import json
|
22 |
+
import os
|
23 |
+
import re
|
24 |
+
from collections import OrderedDict
|
25 |
+
from typing import Any, Dict, Tuple, Union
|
26 |
+
|
27 |
+
import numpy as np
|
28 |
+
|
29 |
+
from huggingface_hub import hf_hub_download
|
30 |
+
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
|
31 |
+
from requests import HTTPError
|
32 |
+
|
33 |
+
from . import __version__
|
34 |
+
from .utils import DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, DummyObject, deprecate, logging
|
35 |
+
|
36 |
+
|
37 |
+
logger = logging.get_logger(__name__)
|
38 |
+
|
39 |
+
_re_configuration_file = re.compile(r"config\.(.*)\.json")
|
40 |
+
|
41 |
+
|
42 |
+
class FrozenDict(OrderedDict):
|
43 |
+
def __init__(self, *args, **kwargs):
|
44 |
+
super().__init__(*args, **kwargs)
|
45 |
+
|
46 |
+
for key, value in self.items():
|
47 |
+
setattr(self, key, value)
|
48 |
+
|
49 |
+
self.__frozen = True
|
50 |
+
|
51 |
+
def __delitem__(self, *args, **kwargs):
|
52 |
+
raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
|
53 |
+
|
54 |
+
def setdefault(self, *args, **kwargs):
|
55 |
+
raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
|
56 |
+
|
57 |
+
def pop(self, *args, **kwargs):
|
58 |
+
raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
|
59 |
+
|
60 |
+
def update(self, *args, **kwargs):
|
61 |
+
raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
|
62 |
+
|
63 |
+
def __setattr__(self, name, value):
|
64 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
65 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
66 |
+
super().__setattr__(name, value)
|
67 |
+
|
68 |
+
def __setitem__(self, name, value):
|
69 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
70 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
71 |
+
super().__setitem__(name, value)
|
72 |
+
|
73 |
+
|
74 |
+
class ConfigMixin:
|
75 |
+
r"""
|
76 |
+
Base class for all configuration classes. Stores all configuration parameters under `self.config` Also handles all
|
77 |
+
methods for loading/downloading/saving classes inheriting from [`ConfigMixin`] with
|
78 |
+
- [`~ConfigMixin.from_config`]
|
79 |
+
- [`~ConfigMixin.save_config`]
|
80 |
+
|
81 |
+
Class attributes:
|
82 |
+
- **config_name** (`str`) -- A filename under which the config should stored when calling
|
83 |
+
[`~ConfigMixin.save_config`] (should be overridden by parent class).
|
84 |
+
- **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
|
85 |
+
overridden by subclass).
|
86 |
+
- **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
|
87 |
+
- **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the init function
|
88 |
+
should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
|
89 |
+
subclass).
|
90 |
+
"""
|
91 |
+
config_name = None
|
92 |
+
ignore_for_config = []
|
93 |
+
has_compatibles = False
|
94 |
+
|
95 |
+
_deprecated_kwargs = []
|
96 |
+
|
97 |
+
def register_to_config(self, **kwargs):
|
98 |
+
if self.config_name is None:
|
99 |
+
raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
|
100 |
+
# Special case for `kwargs` used in deprecation warning added to schedulers
|
101 |
+
# TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
|
102 |
+
# or solve in a more general way.
|
103 |
+
kwargs.pop("kwargs", None)
|
104 |
+
for key, value in kwargs.items():
|
105 |
+
try:
|
106 |
+
setattr(self, key, value)
|
107 |
+
except AttributeError as err:
|
108 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
109 |
+
raise err
|
110 |
+
|
111 |
+
if not hasattr(self, "_internal_dict"):
|
112 |
+
internal_dict = kwargs
|
113 |
+
else:
|
114 |
+
previous_dict = dict(self._internal_dict)
|
115 |
+
internal_dict = {**self._internal_dict, **kwargs}
|
116 |
+
logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
|
117 |
+
|
118 |
+
self._internal_dict = FrozenDict(internal_dict)
|
119 |
+
|
120 |
+
def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
|
121 |
+
"""
|
122 |
+
Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the
|
123 |
+
[`~ConfigMixin.from_config`] class method.
|
124 |
+
|
125 |
+
Args:
|
126 |
+
save_directory (`str` or `os.PathLike`):
|
127 |
+
Directory where the configuration JSON file will be saved (will be created if it does not exist).
|
128 |
+
"""
|
129 |
+
if os.path.isfile(save_directory):
|
130 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
131 |
+
|
132 |
+
os.makedirs(save_directory, exist_ok=True)
|
133 |
+
|
134 |
+
# If we save using the predefined names, we can load using `from_config`
|
135 |
+
output_config_file = os.path.join(save_directory, self.config_name)
|
136 |
+
|
137 |
+
self.to_json_file(output_config_file)
|
138 |
+
logger.info(f"Configuration saved in {output_config_file}")
|
139 |
+
|
140 |
+
@classmethod
|
141 |
+
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
|
142 |
+
r"""
|
143 |
+
Instantiate a Python class from a config dictionary
|
144 |
+
|
145 |
+
Parameters:
|
146 |
+
config (`Dict[str, Any]`):
|
147 |
+
A config dictionary from which the Python class will be instantiated. Make sure to only load
|
148 |
+
configuration files of compatible classes.
|
149 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
150 |
+
Whether kwargs that are not consumed by the Python class should be returned or not.
|
151 |
+
|
152 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
153 |
+
Can be used to update the configuration object (after it being loaded) and initiate the Python class.
|
154 |
+
`**kwargs` will be directly passed to the underlying scheduler/model's `__init__` method and eventually
|
155 |
+
overwrite same named arguments of `config`.
|
156 |
+
|
157 |
+
Examples:
|
158 |
+
|
159 |
+
```python
|
160 |
+
>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
|
161 |
+
|
162 |
+
>>> # Download scheduler from huggingface.co and cache.
|
163 |
+
>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
|
164 |
+
|
165 |
+
>>> # Instantiate DDIM scheduler class with same config as DDPM
|
166 |
+
>>> scheduler = DDIMScheduler.from_config(scheduler.config)
|
167 |
+
|
168 |
+
>>> # Instantiate PNDM scheduler class with same config as DDPM
|
169 |
+
>>> scheduler = PNDMScheduler.from_config(scheduler.config)
|
170 |
+
```
|
171 |
+
"""
|
172 |
+
# <===== TO BE REMOVED WITH DEPRECATION
|
173 |
+
# TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
|
174 |
+
if "pretrained_model_name_or_path" in kwargs:
|
175 |
+
config = kwargs.pop("pretrained_model_name_or_path")
|
176 |
+
|
177 |
+
if config is None:
|
178 |
+
raise ValueError("Please make sure to provide a config as the first positional argument.")
|
179 |
+
# ======>
|
180 |
+
|
181 |
+
if not isinstance(config, dict):
|
182 |
+
deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
|
183 |
+
if "Scheduler" in cls.__name__:
|
184 |
+
deprecation_message += (
|
185 |
+
f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
|
186 |
+
" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
|
187 |
+
" be removed in v1.0.0."
|
188 |
+
)
|
189 |
+
elif "Model" in cls.__name__:
|
190 |
+
deprecation_message += (
|
191 |
+
f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
|
192 |
+
f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
|
193 |
+
" instead. This functionality will be removed in v1.0.0."
|
194 |
+
)
|
195 |
+
deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
|
196 |
+
config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
|
197 |
+
|
198 |
+
init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
|
199 |
+
|
200 |
+
# Allow dtype to be specified on initialization
|
201 |
+
if "dtype" in unused_kwargs:
|
202 |
+
init_dict["dtype"] = unused_kwargs.pop("dtype")
|
203 |
+
|
204 |
+
# add possible deprecated kwargs
|
205 |
+
for deprecated_kwarg in cls._deprecated_kwargs:
|
206 |
+
if deprecated_kwarg in unused_kwargs:
|
207 |
+
init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
|
208 |
+
|
209 |
+
# Return model and optionally state and/or unused_kwargs
|
210 |
+
model = cls(**init_dict)
|
211 |
+
|
212 |
+
# make sure to also save config parameters that might be used for compatible classes
|
213 |
+
model.register_to_config(**hidden_dict)
|
214 |
+
|
215 |
+
# add hidden kwargs of compatible classes to unused_kwargs
|
216 |
+
unused_kwargs = {**unused_kwargs, **hidden_dict}
|
217 |
+
|
218 |
+
if return_unused_kwargs:
|
219 |
+
return (model, unused_kwargs)
|
220 |
+
else:
|
221 |
+
return model
|
222 |
+
|
223 |
+
@classmethod
|
224 |
+
def get_config_dict(cls, *args, **kwargs):
|
225 |
+
deprecation_message = (
|
226 |
+
f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
|
227 |
+
" removed in version v1.0.0"
|
228 |
+
)
|
229 |
+
deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
|
230 |
+
return cls.load_config(*args, **kwargs)
|
231 |
+
|
232 |
+
@classmethod
|
233 |
+
def load_config(
|
234 |
+
cls, pretrained_model_name_or_path: Union[str, os.PathLike], return_unused_kwargs=False, **kwargs
|
235 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
236 |
+
r"""
|
237 |
+
Instantiate a Python class from a config dictionary
|
238 |
+
|
239 |
+
Parameters:
|
240 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
241 |
+
Can be either:
|
242 |
+
|
243 |
+
- A string, the *model id* of a model repo on huggingface.co. Valid model ids should have an
|
244 |
+
organization name, like `google/ddpm-celebahq-256`.
|
245 |
+
- A path to a *directory* containing model weights saved using [`~ConfigMixin.save_config`], e.g.,
|
246 |
+
`./my_model_directory/`.
|
247 |
+
|
248 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
249 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
250 |
+
standard cache should not be used.
|
251 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
252 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
253 |
+
cached versions if they exist.
|
254 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
255 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
256 |
+
file exists.
|
257 |
+
proxies (`Dict[str, str]`, *optional*):
|
258 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
259 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
260 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
261 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
262 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
263 |
+
Whether or not to only look at local files (i.e., do not try to download the model).
|
264 |
+
use_auth_token (`str` or *bool*, *optional*):
|
265 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
266 |
+
when running `transformers-cli login` (stored in `~/.huggingface`).
|
267 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
268 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
269 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
270 |
+
identifier allowed by git.
|
271 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
272 |
+
In case the relevant files are located inside a subfolder of the model repo (either remote in
|
273 |
+
huggingface.co or downloaded locally), you can specify the folder name here.
|
274 |
+
|
275 |
+
<Tip>
|
276 |
+
|
277 |
+
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
|
278 |
+
models](https://huggingface.co/docs/hub/models-gated#gated-models).
|
279 |
+
|
280 |
+
</Tip>
|
281 |
+
|
282 |
+
<Tip>
|
283 |
+
|
284 |
+
Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to
|
285 |
+
use this method in a firewalled environment.
|
286 |
+
|
287 |
+
</Tip>
|
288 |
+
"""
|
289 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
290 |
+
force_download = kwargs.pop("force_download", False)
|
291 |
+
resume_download = kwargs.pop("resume_download", False)
|
292 |
+
proxies = kwargs.pop("proxies", None)
|
293 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
294 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
295 |
+
revision = kwargs.pop("revision", None)
|
296 |
+
_ = kwargs.pop("mirror", None)
|
297 |
+
subfolder = kwargs.pop("subfolder", None)
|
298 |
+
|
299 |
+
user_agent = {"file_type": "config"}
|
300 |
+
|
301 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
302 |
+
|
303 |
+
if cls.config_name is None:
|
304 |
+
raise ValueError(
|
305 |
+
"`self.config_name` is not defined. Note that one should not load a config from "
|
306 |
+
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
|
307 |
+
)
|
308 |
+
|
309 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
310 |
+
config_file = pretrained_model_name_or_path
|
311 |
+
elif os.path.isdir(pretrained_model_name_or_path):
|
312 |
+
if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
|
313 |
+
# Load from a PyTorch checkpoint
|
314 |
+
config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
|
315 |
+
elif subfolder is not None and os.path.isfile(
|
316 |
+
os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
317 |
+
):
|
318 |
+
config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
319 |
+
else:
|
320 |
+
raise EnvironmentError(
|
321 |
+
f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
|
322 |
+
)
|
323 |
+
else:
|
324 |
+
try:
|
325 |
+
# Load from URL or cache if already cached
|
326 |
+
config_file = hf_hub_download(
|
327 |
+
pretrained_model_name_or_path,
|
328 |
+
filename=cls.config_name,
|
329 |
+
cache_dir=cache_dir,
|
330 |
+
force_download=force_download,
|
331 |
+
proxies=proxies,
|
332 |
+
resume_download=resume_download,
|
333 |
+
local_files_only=local_files_only,
|
334 |
+
use_auth_token=use_auth_token,
|
335 |
+
user_agent=user_agent,
|
336 |
+
subfolder=subfolder,
|
337 |
+
revision=revision,
|
338 |
+
)
|
339 |
+
|
340 |
+
except RepositoryNotFoundError:
|
341 |
+
raise EnvironmentError(
|
342 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
|
343 |
+
" listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
|
344 |
+
" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli"
|
345 |
+
" login`."
|
346 |
+
)
|
347 |
+
except RevisionNotFoundError:
|
348 |
+
raise EnvironmentError(
|
349 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
|
350 |
+
" this model name. Check the model page at"
|
351 |
+
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
352 |
+
)
|
353 |
+
except EntryNotFoundError:
|
354 |
+
raise EnvironmentError(
|
355 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
|
356 |
+
)
|
357 |
+
except HTTPError as err:
|
358 |
+
raise EnvironmentError(
|
359 |
+
"There was a specific connection error when trying to load"
|
360 |
+
f" {pretrained_model_name_or_path}:\n{err}"
|
361 |
+
)
|
362 |
+
except ValueError:
|
363 |
+
raise EnvironmentError(
|
364 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
365 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
366 |
+
f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
|
367 |
+
" run the library in offline mode at"
|
368 |
+
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
|
369 |
+
)
|
370 |
+
except EnvironmentError:
|
371 |
+
raise EnvironmentError(
|
372 |
+
f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
373 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
374 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
375 |
+
f"containing a {cls.config_name} file"
|
376 |
+
)
|
377 |
+
|
378 |
+
try:
|
379 |
+
# Load config dict
|
380 |
+
config_dict = cls._dict_from_json_file(config_file)
|
381 |
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
382 |
+
raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
|
383 |
+
|
384 |
+
if return_unused_kwargs:
|
385 |
+
return config_dict, kwargs
|
386 |
+
|
387 |
+
return config_dict
|
388 |
+
|
389 |
+
@staticmethod
|
390 |
+
def _get_init_keys(cls):
|
391 |
+
return set(dict(inspect.signature(cls.__init__).parameters).keys())
|
392 |
+
|
393 |
+
@classmethod
|
394 |
+
def extract_init_dict(cls, config_dict, **kwargs):
|
395 |
+
# 0. Copy origin config dict
|
396 |
+
original_dict = {k: v for k, v in config_dict.items()}
|
397 |
+
|
398 |
+
# 1. Retrieve expected config attributes from __init__ signature
|
399 |
+
expected_keys = cls._get_init_keys(cls)
|
400 |
+
expected_keys.remove("self")
|
401 |
+
# remove general kwargs if present in dict
|
402 |
+
if "kwargs" in expected_keys:
|
403 |
+
expected_keys.remove("kwargs")
|
404 |
+
# remove flax internal keys
|
405 |
+
if hasattr(cls, "_flax_internal_args"):
|
406 |
+
for arg in cls._flax_internal_args:
|
407 |
+
expected_keys.remove(arg)
|
408 |
+
|
409 |
+
# 2. Remove attributes that cannot be expected from expected config attributes
|
410 |
+
# remove keys to be ignored
|
411 |
+
if len(cls.ignore_for_config) > 0:
|
412 |
+
expected_keys = expected_keys - set(cls.ignore_for_config)
|
413 |
+
|
414 |
+
# load diffusers library to import compatible and original scheduler
|
415 |
+
diffusers_library = importlib.import_module(__name__.split(".")[0])
|
416 |
+
|
417 |
+
if cls.has_compatibles:
|
418 |
+
compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
|
419 |
+
else:
|
420 |
+
compatible_classes = []
|
421 |
+
|
422 |
+
expected_keys_comp_cls = set()
|
423 |
+
for c in compatible_classes:
|
424 |
+
expected_keys_c = cls._get_init_keys(c)
|
425 |
+
expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
|
426 |
+
expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
|
427 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
|
428 |
+
|
429 |
+
# remove attributes from orig class that cannot be expected
|
430 |
+
orig_cls_name = config_dict.pop("_class_name", cls.__name__)
|
431 |
+
if orig_cls_name != cls.__name__ and hasattr(diffusers_library, orig_cls_name):
|
432 |
+
orig_cls = getattr(diffusers_library, orig_cls_name)
|
433 |
+
unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
|
434 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
|
435 |
+
|
436 |
+
# remove private attributes
|
437 |
+
config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
|
438 |
+
|
439 |
+
# 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
|
440 |
+
init_dict = {}
|
441 |
+
for key in expected_keys:
|
442 |
+
# if config param is passed to kwarg and is present in config dict
|
443 |
+
# it should overwrite existing config dict key
|
444 |
+
if key in kwargs and key in config_dict:
|
445 |
+
config_dict[key] = kwargs.pop(key)
|
446 |
+
|
447 |
+
if key in kwargs:
|
448 |
+
# overwrite key
|
449 |
+
init_dict[key] = kwargs.pop(key)
|
450 |
+
elif key in config_dict:
|
451 |
+
# use value from config dict
|
452 |
+
init_dict[key] = config_dict.pop(key)
|
453 |
+
|
454 |
+
# 4. Give nice warning if unexpected values have been passed
|
455 |
+
if len(config_dict) > 0:
|
456 |
+
logger.warning(
|
457 |
+
f"The config attributes {config_dict} were passed to {cls.__name__}, "
|
458 |
+
"but are not expected and will be ignored. Please verify your "
|
459 |
+
f"{cls.config_name} configuration file."
|
460 |
+
)
|
461 |
+
|
462 |
+
# 5. Give nice info if config attributes are initiliazed to default because they have not been passed
|
463 |
+
passed_keys = set(init_dict.keys())
|
464 |
+
if len(expected_keys - passed_keys) > 0:
|
465 |
+
logger.info(
|
466 |
+
f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
|
467 |
+
)
|
468 |
+
|
469 |
+
# 6. Define unused keyword arguments
|
470 |
+
unused_kwargs = {**config_dict, **kwargs}
|
471 |
+
|
472 |
+
# 7. Define "hidden" config parameters that were saved for compatible classes
|
473 |
+
hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
|
474 |
+
|
475 |
+
return init_dict, unused_kwargs, hidden_config_dict
|
476 |
+
|
477 |
+
@classmethod
|
478 |
+
def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
|
479 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
480 |
+
text = reader.read()
|
481 |
+
return json.loads(text)
|
482 |
+
|
483 |
+
def __repr__(self):
|
484 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
485 |
+
|
486 |
+
@property
|
487 |
+
def config(self) -> Dict[str, Any]:
|
488 |
+
"""
|
489 |
+
Returns the config of the class as a frozen dictionary
|
490 |
+
|
491 |
+
Returns:
|
492 |
+
`Dict[str, Any]`: Config of the class.
|
493 |
+
"""
|
494 |
+
return self._internal_dict
|
495 |
+
|
496 |
+
def to_json_string(self) -> str:
|
497 |
+
"""
|
498 |
+
Serializes this instance to a JSON string.
|
499 |
+
|
500 |
+
Returns:
|
501 |
+
`str`: String containing all the attributes that make up this configuration instance in JSON format.
|
502 |
+
"""
|
503 |
+
config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
|
504 |
+
config_dict["_class_name"] = self.__class__.__name__
|
505 |
+
config_dict["_diffusers_version"] = __version__
|
506 |
+
|
507 |
+
def to_json_saveable(value):
|
508 |
+
if isinstance(value, np.ndarray):
|
509 |
+
value = value.tolist()
|
510 |
+
return value
|
511 |
+
|
512 |
+
config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
|
513 |
+
return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
514 |
+
|
515 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
516 |
+
"""
|
517 |
+
Save this instance to a JSON file.
|
518 |
+
|
519 |
+
Args:
|
520 |
+
json_file_path (`str` or `os.PathLike`):
|
521 |
+
Path to the JSON file in which this configuration instance's parameters will be saved.
|
522 |
+
"""
|
523 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
524 |
+
writer.write(self.to_json_string())
|
525 |
+
|
526 |
+
|
527 |
+
def register_to_config(init):
|
528 |
+
r"""
|
529 |
+
Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
|
530 |
+
automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
|
531 |
+
shouldn't be registered in the config, use the `ignore_for_config` class variable
|
532 |
+
|
533 |
+
Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
|
534 |
+
"""
|
535 |
+
|
536 |
+
@functools.wraps(init)
|
537 |
+
def inner_init(self, *args, **kwargs):
|
538 |
+
# Ignore private kwargs in the init.
|
539 |
+
init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
|
540 |
+
config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
|
541 |
+
if not isinstance(self, ConfigMixin):
|
542 |
+
raise RuntimeError(
|
543 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
544 |
+
"not inherit from `ConfigMixin`."
|
545 |
+
)
|
546 |
+
|
547 |
+
ignore = getattr(self, "ignore_for_config", [])
|
548 |
+
# Get positional arguments aligned with kwargs
|
549 |
+
new_kwargs = {}
|
550 |
+
signature = inspect.signature(init)
|
551 |
+
parameters = {
|
552 |
+
name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
|
553 |
+
}
|
554 |
+
for arg, name in zip(args, parameters.keys()):
|
555 |
+
new_kwargs[name] = arg
|
556 |
+
|
557 |
+
# Then add all kwargs
|
558 |
+
new_kwargs.update(
|
559 |
+
{
|
560 |
+
k: init_kwargs.get(k, default)
|
561 |
+
for k, default in parameters.items()
|
562 |
+
if k not in ignore and k not in new_kwargs
|
563 |
+
}
|
564 |
+
)
|
565 |
+
new_kwargs = {**config_init_kwargs, **new_kwargs}
|
566 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
567 |
+
init(self, *args, **init_kwargs)
|
568 |
+
|
569 |
+
return inner_init
|
570 |
+
|
571 |
+
|
572 |
+
def flax_register_to_config(cls):
|
573 |
+
original_init = cls.__init__
|
574 |
+
|
575 |
+
@functools.wraps(original_init)
|
576 |
+
def init(self, *args, **kwargs):
|
577 |
+
if not isinstance(self, ConfigMixin):
|
578 |
+
raise RuntimeError(
|
579 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
580 |
+
"not inherit from `ConfigMixin`."
|
581 |
+
)
|
582 |
+
|
583 |
+
# Ignore private kwargs in the init. Retrieve all passed attributes
|
584 |
+
init_kwargs = {k: v for k, v in kwargs.items()}
|
585 |
+
|
586 |
+
# Retrieve default values
|
587 |
+
fields = dataclasses.fields(self)
|
588 |
+
default_kwargs = {}
|
589 |
+
for field in fields:
|
590 |
+
# ignore flax specific attributes
|
591 |
+
if field.name in self._flax_internal_args:
|
592 |
+
continue
|
593 |
+
if type(field.default) == dataclasses._MISSING_TYPE:
|
594 |
+
default_kwargs[field.name] = None
|
595 |
+
else:
|
596 |
+
default_kwargs[field.name] = getattr(self, field.name)
|
597 |
+
|
598 |
+
# Make sure init_kwargs override default kwargs
|
599 |
+
new_kwargs = {**default_kwargs, **init_kwargs}
|
600 |
+
# dtype should be part of `init_kwargs`, but not `new_kwargs`
|
601 |
+
if "dtype" in new_kwargs:
|
602 |
+
new_kwargs.pop("dtype")
|
603 |
+
|
604 |
+
# Get positional arguments aligned with kwargs
|
605 |
+
for i, arg in enumerate(args):
|
606 |
+
name = fields[i].name
|
607 |
+
new_kwargs[name] = arg
|
608 |
+
|
609 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
610 |
+
original_init(self, *args, **kwargs)
|
611 |
+
|
612 |
+
cls.__init__ = init
|
613 |
+
return cls
|
diffusers/dependency_versions_check.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
import sys
|
15 |
+
|
16 |
+
from .dependency_versions_table import deps
|
17 |
+
from .utils.versions import require_version, require_version_core
|
18 |
+
|
19 |
+
|
20 |
+
# define which module versions we always want to check at run time
|
21 |
+
# (usually the ones defined in `install_requires` in setup.py)
|
22 |
+
#
|
23 |
+
# order specific notes:
|
24 |
+
# - tqdm must be checked before tokenizers
|
25 |
+
|
26 |
+
pkgs_to_check_at_runtime = "python tqdm regex requests packaging filelock numpy tokenizers".split()
|
27 |
+
if sys.version_info < (3, 7):
|
28 |
+
pkgs_to_check_at_runtime.append("dataclasses")
|
29 |
+
if sys.version_info < (3, 8):
|
30 |
+
pkgs_to_check_at_runtime.append("importlib_metadata")
|
31 |
+
|
32 |
+
for pkg in pkgs_to_check_at_runtime:
|
33 |
+
if pkg in deps:
|
34 |
+
if pkg == "tokenizers":
|
35 |
+
# must be loaded here, or else tqdm check may fail
|
36 |
+
from .utils import is_tokenizers_available
|
37 |
+
|
38 |
+
if not is_tokenizers_available():
|
39 |
+
continue # not required, check version only if installed
|
40 |
+
|
41 |
+
require_version_core(deps[pkg])
|
42 |
+
else:
|
43 |
+
raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
|
44 |
+
|
45 |
+
|
46 |
+
def dep_version_check(pkg, hint=None):
|
47 |
+
require_version(deps[pkg], hint)
|
diffusers/dependency_versions_table.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# THIS FILE HAS BEEN AUTOGENERATED. To update:
|
2 |
+
# 1. modify the `_deps` dict in setup.py
|
3 |
+
# 2. run `make deps_table_update``
|
4 |
+
deps = {
|
5 |
+
"Pillow": "Pillow",
|
6 |
+
"accelerate": "accelerate>=0.11.0",
|
7 |
+
"black": "black==22.8",
|
8 |
+
"datasets": "datasets",
|
9 |
+
"filelock": "filelock",
|
10 |
+
"flake8": "flake8>=3.8.3",
|
11 |
+
"flax": "flax>=0.4.1",
|
12 |
+
"hf-doc-builder": "hf-doc-builder>=0.3.0",
|
13 |
+
"huggingface-hub": "huggingface-hub>=0.10.0",
|
14 |
+
"importlib_metadata": "importlib_metadata",
|
15 |
+
"isort": "isort>=5.5.4",
|
16 |
+
"jax": "jax>=0.2.8,!=0.3.2",
|
17 |
+
"jaxlib": "jaxlib>=0.1.65",
|
18 |
+
"modelcards": "modelcards>=0.1.4",
|
19 |
+
"numpy": "numpy",
|
20 |
+
"parameterized": "parameterized",
|
21 |
+
"pytest": "pytest",
|
22 |
+
"pytest-timeout": "pytest-timeout",
|
23 |
+
"pytest-xdist": "pytest-xdist",
|
24 |
+
"safetensors": "safetensors",
|
25 |
+
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
|
26 |
+
"scipy": "scipy",
|
27 |
+
"regex": "regex!=2019.12.17",
|
28 |
+
"requests": "requests",
|
29 |
+
"tensorboard": "tensorboard",
|
30 |
+
"torch": "torch>=1.4",
|
31 |
+
"torchvision": "torchvision",
|
32 |
+
"transformers": "transformers>=4.21.0",
|
33 |
+
}
|
diffusers/dynamic_modules_utils.py
ADDED
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Utilities to dynamically load objects from the Hub."""
|
16 |
+
|
17 |
+
import importlib
|
18 |
+
import inspect
|
19 |
+
import os
|
20 |
+
import re
|
21 |
+
import shutil
|
22 |
+
import sys
|
23 |
+
from pathlib import Path
|
24 |
+
from typing import Dict, Optional, Union
|
25 |
+
|
26 |
+
from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
|
27 |
+
|
28 |
+
from .utils import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging
|
29 |
+
|
30 |
+
|
31 |
+
COMMUNITY_PIPELINES_URL = (
|
32 |
+
"https://raw.githubusercontent.com/huggingface/diffusers/main/examples/community/{pipeline}.py"
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
37 |
+
|
38 |
+
|
39 |
+
def init_hf_modules():
|
40 |
+
"""
|
41 |
+
Creates the cache directory for modules with an init, and adds it to the Python path.
|
42 |
+
"""
|
43 |
+
# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
|
44 |
+
if HF_MODULES_CACHE in sys.path:
|
45 |
+
return
|
46 |
+
|
47 |
+
sys.path.append(HF_MODULES_CACHE)
|
48 |
+
os.makedirs(HF_MODULES_CACHE, exist_ok=True)
|
49 |
+
init_path = Path(HF_MODULES_CACHE) / "__init__.py"
|
50 |
+
if not init_path.exists():
|
51 |
+
init_path.touch()
|
52 |
+
|
53 |
+
|
54 |
+
def create_dynamic_module(name: Union[str, os.PathLike]):
|
55 |
+
"""
|
56 |
+
Creates a dynamic module in the cache directory for modules.
|
57 |
+
"""
|
58 |
+
init_hf_modules()
|
59 |
+
dynamic_module_path = Path(HF_MODULES_CACHE) / name
|
60 |
+
# If the parent module does not exist yet, recursively create it.
|
61 |
+
if not dynamic_module_path.parent.exists():
|
62 |
+
create_dynamic_module(dynamic_module_path.parent)
|
63 |
+
os.makedirs(dynamic_module_path, exist_ok=True)
|
64 |
+
init_path = dynamic_module_path / "__init__.py"
|
65 |
+
if not init_path.exists():
|
66 |
+
init_path.touch()
|
67 |
+
|
68 |
+
|
69 |
+
def get_relative_imports(module_file):
|
70 |
+
"""
|
71 |
+
Get the list of modules that are relatively imported in a module file.
|
72 |
+
|
73 |
+
Args:
|
74 |
+
module_file (`str` or `os.PathLike`): The module file to inspect.
|
75 |
+
"""
|
76 |
+
with open(module_file, "r", encoding="utf-8") as f:
|
77 |
+
content = f.read()
|
78 |
+
|
79 |
+
# Imports of the form `import .xxx`
|
80 |
+
relative_imports = re.findall("^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
|
81 |
+
# Imports of the form `from .xxx import yyy`
|
82 |
+
relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
|
83 |
+
# Unique-ify
|
84 |
+
return list(set(relative_imports))
|
85 |
+
|
86 |
+
|
87 |
+
def get_relative_import_files(module_file):
|
88 |
+
"""
|
89 |
+
Get the list of all files that are needed for a given module. Note that this function recurses through the relative
|
90 |
+
imports (if a imports b and b imports c, it will return module files for b and c).
|
91 |
+
|
92 |
+
Args:
|
93 |
+
module_file (`str` or `os.PathLike`): The module file to inspect.
|
94 |
+
"""
|
95 |
+
no_change = False
|
96 |
+
files_to_check = [module_file]
|
97 |
+
all_relative_imports = []
|
98 |
+
|
99 |
+
# Let's recurse through all relative imports
|
100 |
+
while not no_change:
|
101 |
+
new_imports = []
|
102 |
+
for f in files_to_check:
|
103 |
+
new_imports.extend(get_relative_imports(f))
|
104 |
+
|
105 |
+
module_path = Path(module_file).parent
|
106 |
+
new_import_files = [str(module_path / m) for m in new_imports]
|
107 |
+
new_import_files = [f for f in new_import_files if f not in all_relative_imports]
|
108 |
+
files_to_check = [f"{f}.py" for f in new_import_files]
|
109 |
+
|
110 |
+
no_change = len(new_import_files) == 0
|
111 |
+
all_relative_imports.extend(files_to_check)
|
112 |
+
|
113 |
+
return all_relative_imports
|
114 |
+
|
115 |
+
|
116 |
+
def check_imports(filename):
|
117 |
+
"""
|
118 |
+
Check if the current Python environment contains all the libraries that are imported in a file.
|
119 |
+
"""
|
120 |
+
with open(filename, "r", encoding="utf-8") as f:
|
121 |
+
content = f.read()
|
122 |
+
|
123 |
+
# Imports of the form `import xxx`
|
124 |
+
imports = re.findall("^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
|
125 |
+
# Imports of the form `from xxx import yyy`
|
126 |
+
imports += re.findall("^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
|
127 |
+
# Only keep the top-level module
|
128 |
+
imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
|
129 |
+
|
130 |
+
# Unique-ify and test we got them all
|
131 |
+
imports = list(set(imports))
|
132 |
+
missing_packages = []
|
133 |
+
for imp in imports:
|
134 |
+
try:
|
135 |
+
importlib.import_module(imp)
|
136 |
+
except ImportError:
|
137 |
+
missing_packages.append(imp)
|
138 |
+
|
139 |
+
if len(missing_packages) > 0:
|
140 |
+
raise ImportError(
|
141 |
+
"This modeling file requires the following packages that were not found in your environment: "
|
142 |
+
f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`"
|
143 |
+
)
|
144 |
+
|
145 |
+
return get_relative_imports(filename)
|
146 |
+
|
147 |
+
|
148 |
+
def get_class_in_module(class_name, module_path):
|
149 |
+
"""
|
150 |
+
Import a module on the cache directory for modules and extract a class from it.
|
151 |
+
"""
|
152 |
+
module_path = module_path.replace(os.path.sep, ".")
|
153 |
+
module = importlib.import_module(module_path)
|
154 |
+
|
155 |
+
if class_name is None:
|
156 |
+
return find_pipeline_class(module)
|
157 |
+
return getattr(module, class_name)
|
158 |
+
|
159 |
+
|
160 |
+
def find_pipeline_class(loaded_module):
|
161 |
+
"""
|
162 |
+
Retrieve pipeline class that inherits from `DiffusionPipeline`. Note that there has to be exactly one class
|
163 |
+
inheriting from `DiffusionPipeline`.
|
164 |
+
"""
|
165 |
+
from .pipeline_utils import DiffusionPipeline
|
166 |
+
|
167 |
+
cls_members = dict(inspect.getmembers(loaded_module, inspect.isclass))
|
168 |
+
|
169 |
+
pipeline_class = None
|
170 |
+
for cls_name, cls in cls_members.items():
|
171 |
+
if (
|
172 |
+
cls_name != DiffusionPipeline.__name__
|
173 |
+
and issubclass(cls, DiffusionPipeline)
|
174 |
+
and cls.__module__.split(".")[0] != "diffusers"
|
175 |
+
):
|
176 |
+
if pipeline_class is not None:
|
177 |
+
raise ValueError(
|
178 |
+
f"Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"
|
179 |
+
f" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"
|
180 |
+
f" {loaded_module}."
|
181 |
+
)
|
182 |
+
pipeline_class = cls
|
183 |
+
|
184 |
+
return pipeline_class
|
185 |
+
|
186 |
+
|
187 |
+
def get_cached_module_file(
|
188 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
189 |
+
module_file: str,
|
190 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
191 |
+
force_download: bool = False,
|
192 |
+
resume_download: bool = False,
|
193 |
+
proxies: Optional[Dict[str, str]] = None,
|
194 |
+
use_auth_token: Optional[Union[bool, str]] = None,
|
195 |
+
revision: Optional[str] = None,
|
196 |
+
local_files_only: bool = False,
|
197 |
+
):
|
198 |
+
"""
|
199 |
+
Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
|
200 |
+
Transformers module.
|
201 |
+
|
202 |
+
Args:
|
203 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
204 |
+
This can be either:
|
205 |
+
|
206 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
207 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
|
208 |
+
under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
209 |
+
- a path to a *directory* containing a configuration file saved using the
|
210 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
211 |
+
|
212 |
+
module_file (`str`):
|
213 |
+
The name of the module file containing the class to look for.
|
214 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
215 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
216 |
+
cache should not be used.
|
217 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
218 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
219 |
+
exist.
|
220 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
221 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
|
222 |
+
proxies (`Dict[str, str]`, *optional*):
|
223 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
224 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
225 |
+
use_auth_token (`str` or *bool*, *optional*):
|
226 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
227 |
+
when running `transformers-cli login` (stored in `~/.huggingface`).
|
228 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
229 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
230 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
231 |
+
identifier allowed by git.
|
232 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
233 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
234 |
+
|
235 |
+
<Tip>
|
236 |
+
|
237 |
+
You may pass a token in `use_auth_token` if you are not logged in (`huggingface-cli long`) and want to use private
|
238 |
+
or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models).
|
239 |
+
|
240 |
+
</Tip>
|
241 |
+
|
242 |
+
Returns:
|
243 |
+
`str`: The path to the module inside the cache.
|
244 |
+
"""
|
245 |
+
# Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file.
|
246 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
247 |
+
|
248 |
+
module_file_or_url = os.path.join(pretrained_model_name_or_path, module_file)
|
249 |
+
|
250 |
+
if os.path.isfile(module_file_or_url):
|
251 |
+
resolved_module_file = module_file_or_url
|
252 |
+
submodule = "local"
|
253 |
+
elif pretrained_model_name_or_path.count("/") == 0:
|
254 |
+
# community pipeline on GitHub
|
255 |
+
github_url = COMMUNITY_PIPELINES_URL.format(pipeline=pretrained_model_name_or_path)
|
256 |
+
try:
|
257 |
+
resolved_module_file = cached_download(
|
258 |
+
github_url,
|
259 |
+
cache_dir=cache_dir,
|
260 |
+
force_download=force_download,
|
261 |
+
proxies=proxies,
|
262 |
+
resume_download=resume_download,
|
263 |
+
local_files_only=local_files_only,
|
264 |
+
use_auth_token=False,
|
265 |
+
)
|
266 |
+
submodule = "git"
|
267 |
+
module_file = pretrained_model_name_or_path + ".py"
|
268 |
+
except EnvironmentError:
|
269 |
+
logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
|
270 |
+
raise
|
271 |
+
else:
|
272 |
+
try:
|
273 |
+
# Load from URL or cache if already cached
|
274 |
+
resolved_module_file = hf_hub_download(
|
275 |
+
pretrained_model_name_or_path,
|
276 |
+
module_file,
|
277 |
+
cache_dir=cache_dir,
|
278 |
+
force_download=force_download,
|
279 |
+
proxies=proxies,
|
280 |
+
resume_download=resume_download,
|
281 |
+
local_files_only=local_files_only,
|
282 |
+
use_auth_token=use_auth_token,
|
283 |
+
)
|
284 |
+
submodule = os.path.join("local", "--".join(pretrained_model_name_or_path.split("/")))
|
285 |
+
except EnvironmentError:
|
286 |
+
logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
|
287 |
+
raise
|
288 |
+
|
289 |
+
# Check we have all the requirements in our environment
|
290 |
+
modules_needed = check_imports(resolved_module_file)
|
291 |
+
|
292 |
+
# Now we move the module inside our cached dynamic modules.
|
293 |
+
full_submodule = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
|
294 |
+
create_dynamic_module(full_submodule)
|
295 |
+
submodule_path = Path(HF_MODULES_CACHE) / full_submodule
|
296 |
+
if submodule == "local" or submodule == "git":
|
297 |
+
# We always copy local files (we could hash the file to see if there was a change, and give them the name of
|
298 |
+
# that hash, to only copy when there is a modification but it seems overkill for now).
|
299 |
+
# The only reason we do the copy is to avoid putting too many folders in sys.path.
|
300 |
+
shutil.copy(resolved_module_file, submodule_path / module_file)
|
301 |
+
for module_needed in modules_needed:
|
302 |
+
module_needed = f"{module_needed}.py"
|
303 |
+
shutil.copy(os.path.join(pretrained_model_name_or_path, module_needed), submodule_path / module_needed)
|
304 |
+
else:
|
305 |
+
# Get the commit hash
|
306 |
+
# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
|
307 |
+
if isinstance(use_auth_token, str):
|
308 |
+
token = use_auth_token
|
309 |
+
elif use_auth_token is True:
|
310 |
+
token = HfFolder.get_token()
|
311 |
+
else:
|
312 |
+
token = None
|
313 |
+
|
314 |
+
commit_hash = model_info(pretrained_model_name_or_path, revision=revision, token=token).sha
|
315 |
+
|
316 |
+
# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
|
317 |
+
# benefit of versioning.
|
318 |
+
submodule_path = submodule_path / commit_hash
|
319 |
+
full_submodule = full_submodule + os.path.sep + commit_hash
|
320 |
+
create_dynamic_module(full_submodule)
|
321 |
+
|
322 |
+
if not (submodule_path / module_file).exists():
|
323 |
+
shutil.copy(resolved_module_file, submodule_path / module_file)
|
324 |
+
# Make sure we also have every file with relative
|
325 |
+
for module_needed in modules_needed:
|
326 |
+
if not (submodule_path / module_needed).exists():
|
327 |
+
get_cached_module_file(
|
328 |
+
pretrained_model_name_or_path,
|
329 |
+
f"{module_needed}.py",
|
330 |
+
cache_dir=cache_dir,
|
331 |
+
force_download=force_download,
|
332 |
+
resume_download=resume_download,
|
333 |
+
proxies=proxies,
|
334 |
+
use_auth_token=use_auth_token,
|
335 |
+
revision=revision,
|
336 |
+
local_files_only=local_files_only,
|
337 |
+
)
|
338 |
+
return os.path.join(full_submodule, module_file)
|
339 |
+
|
340 |
+
|
341 |
+
def get_class_from_dynamic_module(
|
342 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
343 |
+
module_file: str,
|
344 |
+
class_name: Optional[str] = None,
|
345 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
346 |
+
force_download: bool = False,
|
347 |
+
resume_download: bool = False,
|
348 |
+
proxies: Optional[Dict[str, str]] = None,
|
349 |
+
use_auth_token: Optional[Union[bool, str]] = None,
|
350 |
+
revision: Optional[str] = None,
|
351 |
+
local_files_only: bool = False,
|
352 |
+
**kwargs,
|
353 |
+
):
|
354 |
+
"""
|
355 |
+
Extracts a class from a module file, present in the local folder or repository of a model.
|
356 |
+
|
357 |
+
<Tip warning={true}>
|
358 |
+
|
359 |
+
Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should
|
360 |
+
therefore only be called on trusted repos.
|
361 |
+
|
362 |
+
</Tip>
|
363 |
+
|
364 |
+
Args:
|
365 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
366 |
+
This can be either:
|
367 |
+
|
368 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
369 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
|
370 |
+
under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
371 |
+
- a path to a *directory* containing a configuration file saved using the
|
372 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
373 |
+
|
374 |
+
module_file (`str`):
|
375 |
+
The name of the module file containing the class to look for.
|
376 |
+
class_name (`str`):
|
377 |
+
The name of the class to import in the module.
|
378 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
379 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
380 |
+
cache should not be used.
|
381 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
382 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
383 |
+
exist.
|
384 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
385 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
|
386 |
+
proxies (`Dict[str, str]`, *optional*):
|
387 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
388 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
389 |
+
use_auth_token (`str` or `bool`, *optional*):
|
390 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
391 |
+
when running `transformers-cli login` (stored in `~/.huggingface`).
|
392 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
393 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
394 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
395 |
+
identifier allowed by git.
|
396 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
397 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
398 |
+
|
399 |
+
<Tip>
|
400 |
+
|
401 |
+
You may pass a token in `use_auth_token` if you are not logged in (`huggingface-cli long`) and want to use private
|
402 |
+
or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models).
|
403 |
+
|
404 |
+
</Tip>
|
405 |
+
|
406 |
+
Returns:
|
407 |
+
`type`: The class, dynamically imported from the module.
|
408 |
+
|
409 |
+
Examples:
|
410 |
+
|
411 |
+
```python
|
412 |
+
# Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
|
413 |
+
# module.
|
414 |
+
cls = get_class_from_dynamic_module("sgugger/my-bert-model", "modeling.py", "MyBertModel")
|
415 |
+
```"""
|
416 |
+
# And lastly we get the class inside our newly created module
|
417 |
+
final_module = get_cached_module_file(
|
418 |
+
pretrained_model_name_or_path,
|
419 |
+
module_file,
|
420 |
+
cache_dir=cache_dir,
|
421 |
+
force_download=force_download,
|
422 |
+
resume_download=resume_download,
|
423 |
+
proxies=proxies,
|
424 |
+
use_auth_token=use_auth_token,
|
425 |
+
revision=revision,
|
426 |
+
local_files_only=local_files_only,
|
427 |
+
)
|
428 |
+
return get_class_in_module(class_name, final_module.replace(".py", ""))
|
diffusers/experimental/README.md
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🧨 Diffusers Experimental
|
2 |
+
|
3 |
+
We are adding experimental code to support novel applications and usages of the Diffusers library.
|
4 |
+
Currently, the following experiments are supported:
|
5 |
+
* Reinforcement learning via an implementation of the [Diffuser](https://arxiv.org/abs/2205.09991) model.
|
diffusers/experimental/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .rl import ValueGuidedRLPipeline
|
diffusers/experimental/rl/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .value_guided_sampling import ValueGuidedRLPipeline
|
diffusers/experimental/rl/value_guided_sampling.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import numpy as np
|
16 |
+
import torch
|
17 |
+
|
18 |
+
import tqdm
|
19 |
+
|
20 |
+
from ...models.unet_1d import UNet1DModel
|
21 |
+
from ...pipeline_utils import DiffusionPipeline
|
22 |
+
from ...utils.dummy_pt_objects import DDPMScheduler
|
23 |
+
|
24 |
+
|
25 |
+
class ValueGuidedRLPipeline(DiffusionPipeline):
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
value_function: UNet1DModel,
|
29 |
+
unet: UNet1DModel,
|
30 |
+
scheduler: DDPMScheduler,
|
31 |
+
env,
|
32 |
+
):
|
33 |
+
super().__init__()
|
34 |
+
self.value_function = value_function
|
35 |
+
self.unet = unet
|
36 |
+
self.scheduler = scheduler
|
37 |
+
self.env = env
|
38 |
+
self.data = env.get_dataset()
|
39 |
+
self.means = dict()
|
40 |
+
for key in self.data.keys():
|
41 |
+
try:
|
42 |
+
self.means[key] = self.data[key].mean()
|
43 |
+
except:
|
44 |
+
pass
|
45 |
+
self.stds = dict()
|
46 |
+
for key in self.data.keys():
|
47 |
+
try:
|
48 |
+
self.stds[key] = self.data[key].std()
|
49 |
+
except:
|
50 |
+
pass
|
51 |
+
self.state_dim = env.observation_space.shape[0]
|
52 |
+
self.action_dim = env.action_space.shape[0]
|
53 |
+
|
54 |
+
def normalize(self, x_in, key):
|
55 |
+
return (x_in - self.means[key]) / self.stds[key]
|
56 |
+
|
57 |
+
def de_normalize(self, x_in, key):
|
58 |
+
return x_in * self.stds[key] + self.means[key]
|
59 |
+
|
60 |
+
def to_torch(self, x_in):
|
61 |
+
if type(x_in) is dict:
|
62 |
+
return {k: self.to_torch(v) for k, v in x_in.items()}
|
63 |
+
elif torch.is_tensor(x_in):
|
64 |
+
return x_in.to(self.unet.device)
|
65 |
+
return torch.tensor(x_in, device=self.unet.device)
|
66 |
+
|
67 |
+
def reset_x0(self, x_in, cond, act_dim):
|
68 |
+
for key, val in cond.items():
|
69 |
+
x_in[:, key, act_dim:] = val.clone()
|
70 |
+
return x_in
|
71 |
+
|
72 |
+
def run_diffusion(self, x, conditions, n_guide_steps, scale):
|
73 |
+
batch_size = x.shape[0]
|
74 |
+
y = None
|
75 |
+
for i in tqdm.tqdm(self.scheduler.timesteps):
|
76 |
+
# create batch of timesteps to pass into model
|
77 |
+
timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
|
78 |
+
for _ in range(n_guide_steps):
|
79 |
+
with torch.enable_grad():
|
80 |
+
x.requires_grad_()
|
81 |
+
y = self.value_function(x.permute(0, 2, 1), timesteps).sample
|
82 |
+
grad = torch.autograd.grad([y.sum()], [x])[0]
|
83 |
+
|
84 |
+
posterior_variance = self.scheduler._get_variance(i)
|
85 |
+
model_std = torch.exp(0.5 * posterior_variance)
|
86 |
+
grad = model_std * grad
|
87 |
+
grad[timesteps < 2] = 0
|
88 |
+
x = x.detach()
|
89 |
+
x = x + scale * grad
|
90 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
91 |
+
prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
|
92 |
+
# TODO: set prediction_type when instantiating the model
|
93 |
+
x = self.scheduler.step(prev_x, i, x, predict_epsilon=False)["prev_sample"]
|
94 |
+
|
95 |
+
# apply conditions to the trajectory
|
96 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
97 |
+
x = self.to_torch(x)
|
98 |
+
return x, y
|
99 |
+
|
100 |
+
def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
|
101 |
+
# normalize the observations and create batch dimension
|
102 |
+
obs = self.normalize(obs, "observations")
|
103 |
+
obs = obs[None].repeat(batch_size, axis=0)
|
104 |
+
|
105 |
+
conditions = {0: self.to_torch(obs)}
|
106 |
+
shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
|
107 |
+
|
108 |
+
# generate initial noise and apply our conditions (to make the trajectories start at current state)
|
109 |
+
x1 = torch.randn(shape, device=self.unet.device)
|
110 |
+
x = self.reset_x0(x1, conditions, self.action_dim)
|
111 |
+
x = self.to_torch(x)
|
112 |
+
|
113 |
+
# run the diffusion process
|
114 |
+
x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
|
115 |
+
|
116 |
+
# sort output trajectories by value
|
117 |
+
sorted_idx = y.argsort(0, descending=True).squeeze()
|
118 |
+
sorted_values = x[sorted_idx]
|
119 |
+
actions = sorted_values[:, :, : self.action_dim]
|
120 |
+
actions = actions.detach().cpu().numpy()
|
121 |
+
denorm_actions = self.de_normalize(actions, key="actions")
|
122 |
+
|
123 |
+
# select the action with the highest value
|
124 |
+
if y is not None:
|
125 |
+
selected_index = 0
|
126 |
+
else:
|
127 |
+
# if we didn't run value guiding, select a random action
|
128 |
+
selected_index = np.random.randint(0, batch_size)
|
129 |
+
denorm_actions = denorm_actions[selected_index, 0]
|
130 |
+
return denorm_actions
|
diffusers/hub_utils.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
|
17 |
+
import os
|
18 |
+
import sys
|
19 |
+
from pathlib import Path
|
20 |
+
from typing import Dict, Optional, Union
|
21 |
+
from uuid import uuid4
|
22 |
+
|
23 |
+
from huggingface_hub import HfFolder, whoami
|
24 |
+
|
25 |
+
from . import __version__
|
26 |
+
from .utils import ENV_VARS_TRUE_VALUES, logging
|
27 |
+
from .utils.import_utils import (
|
28 |
+
_flax_version,
|
29 |
+
_jax_version,
|
30 |
+
_onnxruntime_version,
|
31 |
+
_torch_version,
|
32 |
+
is_flax_available,
|
33 |
+
is_modelcards_available,
|
34 |
+
is_onnx_available,
|
35 |
+
is_torch_available,
|
36 |
+
)
|
37 |
+
|
38 |
+
|
39 |
+
if is_modelcards_available():
|
40 |
+
from modelcards import CardData, ModelCard
|
41 |
+
|
42 |
+
|
43 |
+
logger = logging.get_logger(__name__)
|
44 |
+
|
45 |
+
|
46 |
+
MODEL_CARD_TEMPLATE_PATH = Path(__file__).parent / "utils" / "model_card_template.md"
|
47 |
+
SESSION_ID = uuid4().hex
|
48 |
+
DISABLE_TELEMETRY = os.getenv("DISABLE_TELEMETRY", "").upper() in ENV_VARS_TRUE_VALUES
|
49 |
+
|
50 |
+
|
51 |
+
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
|
52 |
+
"""
|
53 |
+
Formats a user-agent string with basic info about a request.
|
54 |
+
"""
|
55 |
+
ua = f"diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
|
56 |
+
if DISABLE_TELEMETRY:
|
57 |
+
return ua + "; telemetry/off"
|
58 |
+
if is_torch_available():
|
59 |
+
ua += f"; torch/{_torch_version}"
|
60 |
+
if is_flax_available():
|
61 |
+
ua += f"; jax/{_jax_version}"
|
62 |
+
ua += f"; flax/{_flax_version}"
|
63 |
+
if is_onnx_available():
|
64 |
+
ua += f"; onnxruntime/{_onnxruntime_version}"
|
65 |
+
# CI will set this value to True
|
66 |
+
if os.environ.get("DIFFUSERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES:
|
67 |
+
ua += "; is_ci/true"
|
68 |
+
if isinstance(user_agent, dict):
|
69 |
+
ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
|
70 |
+
elif isinstance(user_agent, str):
|
71 |
+
ua += "; " + user_agent
|
72 |
+
return ua
|
73 |
+
|
74 |
+
|
75 |
+
def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
|
76 |
+
if token is None:
|
77 |
+
token = HfFolder.get_token()
|
78 |
+
if organization is None:
|
79 |
+
username = whoami(token)["name"]
|
80 |
+
return f"{username}/{model_id}"
|
81 |
+
else:
|
82 |
+
return f"{organization}/{model_id}"
|
83 |
+
|
84 |
+
|
85 |
+
def create_model_card(args, model_name):
|
86 |
+
if not is_modelcards_available:
|
87 |
+
raise ValueError(
|
88 |
+
"Please make sure to have `modelcards` installed when using the `create_model_card` function. You can"
|
89 |
+
" install the package with `pip install modelcards`."
|
90 |
+
)
|
91 |
+
|
92 |
+
if hasattr(args, "local_rank") and args.local_rank not in [-1, 0]:
|
93 |
+
return
|
94 |
+
|
95 |
+
hub_token = args.hub_token if hasattr(args, "hub_token") else None
|
96 |
+
repo_name = get_full_repo_name(model_name, token=hub_token)
|
97 |
+
|
98 |
+
model_card = ModelCard.from_template(
|
99 |
+
card_data=CardData( # Card metadata object that will be converted to YAML block
|
100 |
+
language="en",
|
101 |
+
license="apache-2.0",
|
102 |
+
library_name="diffusers",
|
103 |
+
tags=[],
|
104 |
+
datasets=args.dataset_name,
|
105 |
+
metrics=[],
|
106 |
+
),
|
107 |
+
template_path=MODEL_CARD_TEMPLATE_PATH,
|
108 |
+
model_name=model_name,
|
109 |
+
repo_name=repo_name,
|
110 |
+
dataset_name=args.dataset_name if hasattr(args, "dataset_name") else None,
|
111 |
+
learning_rate=args.learning_rate,
|
112 |
+
train_batch_size=args.train_batch_size,
|
113 |
+
eval_batch_size=args.eval_batch_size,
|
114 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps
|
115 |
+
if hasattr(args, "gradient_accumulation_steps")
|
116 |
+
else None,
|
117 |
+
adam_beta1=args.adam_beta1 if hasattr(args, "adam_beta1") else None,
|
118 |
+
adam_beta2=args.adam_beta2 if hasattr(args, "adam_beta2") else None,
|
119 |
+
adam_weight_decay=args.adam_weight_decay if hasattr(args, "adam_weight_decay") else None,
|
120 |
+
adam_epsilon=args.adam_epsilon if hasattr(args, "adam_epsilon") else None,
|
121 |
+
lr_scheduler=args.lr_scheduler if hasattr(args, "lr_scheduler") else None,
|
122 |
+
lr_warmup_steps=args.lr_warmup_steps if hasattr(args, "lr_warmup_steps") else None,
|
123 |
+
ema_inv_gamma=args.ema_inv_gamma if hasattr(args, "ema_inv_gamma") else None,
|
124 |
+
ema_power=args.ema_power if hasattr(args, "ema_power") else None,
|
125 |
+
ema_max_decay=args.ema_max_decay if hasattr(args, "ema_max_decay") else None,
|
126 |
+
mixed_precision=args.mixed_precision,
|
127 |
+
)
|
128 |
+
|
129 |
+
card_path = os.path.join(args.output_dir, "README.md")
|
130 |
+
model_card.save(card_path)
|
diffusers/modeling_flax_pytorch_utils.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" PyTorch - Flax general utilities."""
|
16 |
+
import re
|
17 |
+
|
18 |
+
import jax.numpy as jnp
|
19 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
20 |
+
from jax.random import PRNGKey
|
21 |
+
|
22 |
+
from .utils import logging
|
23 |
+
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
|
28 |
+
def rename_key(key):
|
29 |
+
regex = r"\w+[.]\d+"
|
30 |
+
pats = re.findall(regex, key)
|
31 |
+
for pat in pats:
|
32 |
+
key = key.replace(pat, "_".join(pat.split(".")))
|
33 |
+
return key
|
34 |
+
|
35 |
+
|
36 |
+
#####################
|
37 |
+
# PyTorch => Flax #
|
38 |
+
#####################
|
39 |
+
|
40 |
+
# Adapted from https://github.com/huggingface/transformers/blob/c603c80f46881ae18b2ca50770ef65fa4033eacd/src/transformers/modeling_flax_pytorch_utils.py#L69
|
41 |
+
# and https://github.com/patil-suraj/stable-diffusion-jax/blob/main/stable_diffusion_jax/convert_diffusers_to_jax.py
|
42 |
+
def rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict):
|
43 |
+
"""Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
|
44 |
+
|
45 |
+
# conv norm or layer norm
|
46 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
|
47 |
+
if (
|
48 |
+
any("norm" in str_ for str_ in pt_tuple_key)
|
49 |
+
and (pt_tuple_key[-1] == "bias")
|
50 |
+
and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
|
51 |
+
and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
|
52 |
+
):
|
53 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
|
54 |
+
return renamed_pt_tuple_key, pt_tensor
|
55 |
+
elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
|
56 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
|
57 |
+
return renamed_pt_tuple_key, pt_tensor
|
58 |
+
|
59 |
+
# embedding
|
60 |
+
if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
|
61 |
+
pt_tuple_key = pt_tuple_key[:-1] + ("embedding",)
|
62 |
+
return renamed_pt_tuple_key, pt_tensor
|
63 |
+
|
64 |
+
# conv layer
|
65 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
|
66 |
+
if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
|
67 |
+
pt_tensor = pt_tensor.transpose(2, 3, 1, 0)
|
68 |
+
return renamed_pt_tuple_key, pt_tensor
|
69 |
+
|
70 |
+
# linear layer
|
71 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
|
72 |
+
if pt_tuple_key[-1] == "weight":
|
73 |
+
pt_tensor = pt_tensor.T
|
74 |
+
return renamed_pt_tuple_key, pt_tensor
|
75 |
+
|
76 |
+
# old PyTorch layer norm weight
|
77 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",)
|
78 |
+
if pt_tuple_key[-1] == "gamma":
|
79 |
+
return renamed_pt_tuple_key, pt_tensor
|
80 |
+
|
81 |
+
# old PyTorch layer norm bias
|
82 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",)
|
83 |
+
if pt_tuple_key[-1] == "beta":
|
84 |
+
return renamed_pt_tuple_key, pt_tensor
|
85 |
+
|
86 |
+
return pt_tuple_key, pt_tensor
|
87 |
+
|
88 |
+
|
89 |
+
def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model, init_key=42):
|
90 |
+
# Step 1: Convert pytorch tensor to numpy
|
91 |
+
pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
|
92 |
+
|
93 |
+
# Step 2: Since the model is stateless, get random Flax params
|
94 |
+
random_flax_params = flax_model.init_weights(PRNGKey(init_key))
|
95 |
+
|
96 |
+
random_flax_state_dict = flatten_dict(random_flax_params)
|
97 |
+
flax_state_dict = {}
|
98 |
+
|
99 |
+
# Need to change some parameters name to match Flax names
|
100 |
+
for pt_key, pt_tensor in pt_state_dict.items():
|
101 |
+
renamed_pt_key = rename_key(pt_key)
|
102 |
+
pt_tuple_key = tuple(renamed_pt_key.split("."))
|
103 |
+
|
104 |
+
# Correctly rename weight parameters
|
105 |
+
flax_key, flax_tensor = rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict)
|
106 |
+
|
107 |
+
if flax_key in random_flax_state_dict:
|
108 |
+
if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
|
109 |
+
raise ValueError(
|
110 |
+
f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
|
111 |
+
f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
|
112 |
+
)
|
113 |
+
|
114 |
+
# also add unexpected weight so that warning is thrown
|
115 |
+
flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
|
116 |
+
|
117 |
+
return unflatten_dict(flax_state_dict)
|
diffusers/modeling_flax_utils.py
ADDED
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import os
|
17 |
+
from pickle import UnpicklingError
|
18 |
+
from typing import Any, Dict, Union
|
19 |
+
|
20 |
+
import jax
|
21 |
+
import jax.numpy as jnp
|
22 |
+
import msgpack.exceptions
|
23 |
+
from flax.core.frozen_dict import FrozenDict, unfreeze
|
24 |
+
from flax.serialization import from_bytes, to_bytes
|
25 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
26 |
+
from huggingface_hub import hf_hub_download
|
27 |
+
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
|
28 |
+
from requests import HTTPError
|
29 |
+
|
30 |
+
from . import __version__, is_torch_available
|
31 |
+
from .modeling_flax_pytorch_utils import convert_pytorch_state_dict_to_flax
|
32 |
+
from .utils import (
|
33 |
+
CONFIG_NAME,
|
34 |
+
DIFFUSERS_CACHE,
|
35 |
+
FLAX_WEIGHTS_NAME,
|
36 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
37 |
+
WEIGHTS_NAME,
|
38 |
+
logging,
|
39 |
+
)
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
|
45 |
+
class FlaxModelMixin:
|
46 |
+
r"""
|
47 |
+
Base class for all flax models.
|
48 |
+
|
49 |
+
[`FlaxModelMixin`] takes care of storing the configuration of the models and handles methods for loading,
|
50 |
+
downloading and saving models.
|
51 |
+
"""
|
52 |
+
config_name = CONFIG_NAME
|
53 |
+
_automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
|
54 |
+
_flax_internal_args = ["name", "parent", "dtype"]
|
55 |
+
|
56 |
+
@classmethod
|
57 |
+
def _from_config(cls, config, **kwargs):
|
58 |
+
"""
|
59 |
+
All context managers that the model should be initialized under go here.
|
60 |
+
"""
|
61 |
+
return cls(config, **kwargs)
|
62 |
+
|
63 |
+
def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
|
64 |
+
"""
|
65 |
+
Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
|
66 |
+
"""
|
67 |
+
|
68 |
+
# taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
|
69 |
+
def conditional_cast(param):
|
70 |
+
if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
|
71 |
+
param = param.astype(dtype)
|
72 |
+
return param
|
73 |
+
|
74 |
+
if mask is None:
|
75 |
+
return jax.tree_map(conditional_cast, params)
|
76 |
+
|
77 |
+
flat_params = flatten_dict(params)
|
78 |
+
flat_mask, _ = jax.tree_flatten(mask)
|
79 |
+
|
80 |
+
for masked, key in zip(flat_mask, flat_params.keys()):
|
81 |
+
if masked:
|
82 |
+
param = flat_params[key]
|
83 |
+
flat_params[key] = conditional_cast(param)
|
84 |
+
|
85 |
+
return unflatten_dict(flat_params)
|
86 |
+
|
87 |
+
def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
88 |
+
r"""
|
89 |
+
Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
|
90 |
+
the `params` in place.
|
91 |
+
|
92 |
+
This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full
|
93 |
+
half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
|
94 |
+
|
95 |
+
Arguments:
|
96 |
+
params (`Union[Dict, FrozenDict]`):
|
97 |
+
A `PyTree` of model parameters.
|
98 |
+
mask (`Union[Dict, FrozenDict]`):
|
99 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
100 |
+
you want to cast, and should be `False` for those you want to skip.
|
101 |
+
|
102 |
+
Examples:
|
103 |
+
|
104 |
+
```python
|
105 |
+
>>> from diffusers import FlaxUNet2DConditionModel
|
106 |
+
|
107 |
+
>>> # load model
|
108 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
109 |
+
>>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
|
110 |
+
>>> params = model.to_bf16(params)
|
111 |
+
>>> # If you don't want to cast certain parameters (for example layer norm bias and scale)
|
112 |
+
>>> # then pass the mask as follows
|
113 |
+
>>> from flax import traverse_util
|
114 |
+
|
115 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
116 |
+
>>> flat_params = traverse_util.flatten_dict(params)
|
117 |
+
>>> mask = {
|
118 |
+
... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
|
119 |
+
... for path in flat_params
|
120 |
+
... }
|
121 |
+
>>> mask = traverse_util.unflatten_dict(mask)
|
122 |
+
>>> params = model.to_bf16(params, mask)
|
123 |
+
```"""
|
124 |
+
return self._cast_floating_to(params, jnp.bfloat16, mask)
|
125 |
+
|
126 |
+
def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
127 |
+
r"""
|
128 |
+
Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
|
129 |
+
model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
|
130 |
+
|
131 |
+
Arguments:
|
132 |
+
params (`Union[Dict, FrozenDict]`):
|
133 |
+
A `PyTree` of model parameters.
|
134 |
+
mask (`Union[Dict, FrozenDict]`):
|
135 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
136 |
+
you want to cast, and should be `False` for those you want to skip
|
137 |
+
|
138 |
+
Examples:
|
139 |
+
|
140 |
+
```python
|
141 |
+
>>> from diffusers import FlaxUNet2DConditionModel
|
142 |
+
|
143 |
+
>>> # Download model and configuration from huggingface.co
|
144 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
145 |
+
>>> # By default, the model params will be in fp32, to illustrate the use of this method,
|
146 |
+
>>> # we'll first cast to fp16 and back to fp32
|
147 |
+
>>> params = model.to_f16(params)
|
148 |
+
>>> # now cast back to fp32
|
149 |
+
>>> params = model.to_fp32(params)
|
150 |
+
```"""
|
151 |
+
return self._cast_floating_to(params, jnp.float32, mask)
|
152 |
+
|
153 |
+
def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
154 |
+
r"""
|
155 |
+
Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
|
156 |
+
`params` in place.
|
157 |
+
|
158 |
+
This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full
|
159 |
+
half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
|
160 |
+
|
161 |
+
Arguments:
|
162 |
+
params (`Union[Dict, FrozenDict]`):
|
163 |
+
A `PyTree` of model parameters.
|
164 |
+
mask (`Union[Dict, FrozenDict]`):
|
165 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
166 |
+
you want to cast, and should be `False` for those you want to skip
|
167 |
+
|
168 |
+
Examples:
|
169 |
+
|
170 |
+
```python
|
171 |
+
>>> from diffusers import FlaxUNet2DConditionModel
|
172 |
+
|
173 |
+
>>> # load model
|
174 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
175 |
+
>>> # By default, the model params will be in fp32, to cast these to float16
|
176 |
+
>>> params = model.to_fp16(params)
|
177 |
+
>>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
|
178 |
+
>>> # then pass the mask as follows
|
179 |
+
>>> from flax import traverse_util
|
180 |
+
|
181 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
182 |
+
>>> flat_params = traverse_util.flatten_dict(params)
|
183 |
+
>>> mask = {
|
184 |
+
... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
|
185 |
+
... for path in flat_params
|
186 |
+
... }
|
187 |
+
>>> mask = traverse_util.unflatten_dict(mask)
|
188 |
+
>>> params = model.to_fp16(params, mask)
|
189 |
+
```"""
|
190 |
+
return self._cast_floating_to(params, jnp.float16, mask)
|
191 |
+
|
192 |
+
def init_weights(self, rng: jax.random.PRNGKey) -> Dict:
|
193 |
+
raise NotImplementedError(f"init_weights method has to be implemented for {self}")
|
194 |
+
|
195 |
+
@classmethod
|
196 |
+
def from_pretrained(
|
197 |
+
cls,
|
198 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
199 |
+
dtype: jnp.dtype = jnp.float32,
|
200 |
+
*model_args,
|
201 |
+
**kwargs,
|
202 |
+
):
|
203 |
+
r"""
|
204 |
+
Instantiate a pretrained flax model from a pre-trained model configuration.
|
205 |
+
|
206 |
+
The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
|
207 |
+
pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
|
208 |
+
task.
|
209 |
+
|
210 |
+
The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
|
211 |
+
weights are discarded.
|
212 |
+
|
213 |
+
Parameters:
|
214 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
215 |
+
Can be either:
|
216 |
+
|
217 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
218 |
+
Valid model ids are namespaced under a user or organization name, like
|
219 |
+
`runwayml/stable-diffusion-v1-5`.
|
220 |
+
- A path to a *directory* containing model weights saved using [`~ModelMixin.save_pretrained`],
|
221 |
+
e.g., `./my_model_directory/`.
|
222 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
223 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
224 |
+
`jax.numpy.bfloat16` (on TPUs).
|
225 |
+
|
226 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
227 |
+
specified all the computation will be performed with the given `dtype`.
|
228 |
+
|
229 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
230 |
+
parameters.**
|
231 |
+
|
232 |
+
If you wish to change the dtype of the model parameters, see [`~ModelMixin.to_fp16`] and
|
233 |
+
[`~ModelMixin.to_bf16`].
|
234 |
+
model_args (sequence of positional arguments, *optional*):
|
235 |
+
All remaining positional arguments will be passed to the underlying model's `__init__` method.
|
236 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
237 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
238 |
+
standard cache should not be used.
|
239 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
240 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
241 |
+
cached versions if they exist.
|
242 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
243 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
244 |
+
file exists.
|
245 |
+
proxies (`Dict[str, str]`, *optional*):
|
246 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
247 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
248 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
249 |
+
Whether or not to only look at local files (i.e., do not try to download the model).
|
250 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
251 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
252 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
253 |
+
identifier allowed by git.
|
254 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
255 |
+
Load the model weights from a PyTorch checkpoint save file.
|
256 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
257 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
258 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
259 |
+
automatically loaded:
|
260 |
+
|
261 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
262 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
263 |
+
already been done)
|
264 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
265 |
+
initialization function ([`~ConfigMixin.from_config`]). Each key of `kwargs` that corresponds to
|
266 |
+
a configuration attribute will be used to override said attribute with the supplied `kwargs`
|
267 |
+
value. Remaining keys that do not correspond to any configuration attribute will be passed to the
|
268 |
+
underlying model's `__init__` function.
|
269 |
+
|
270 |
+
Examples:
|
271 |
+
|
272 |
+
```python
|
273 |
+
>>> from diffusers import FlaxUNet2DConditionModel
|
274 |
+
|
275 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
276 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
|
277 |
+
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
|
278 |
+
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")
|
279 |
+
```"""
|
280 |
+
config = kwargs.pop("config", None)
|
281 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
282 |
+
force_download = kwargs.pop("force_download", False)
|
283 |
+
from_pt = kwargs.pop("from_pt", False)
|
284 |
+
resume_download = kwargs.pop("resume_download", False)
|
285 |
+
proxies = kwargs.pop("proxies", None)
|
286 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
287 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
288 |
+
revision = kwargs.pop("revision", None)
|
289 |
+
subfolder = kwargs.pop("subfolder", None)
|
290 |
+
|
291 |
+
user_agent = {
|
292 |
+
"diffusers": __version__,
|
293 |
+
"file_type": "model",
|
294 |
+
"framework": "flax",
|
295 |
+
}
|
296 |
+
|
297 |
+
# Load config if we don't provide a configuration
|
298 |
+
config_path = config if config is not None else pretrained_model_name_or_path
|
299 |
+
model, model_kwargs = cls.from_config(
|
300 |
+
config_path,
|
301 |
+
cache_dir=cache_dir,
|
302 |
+
return_unused_kwargs=True,
|
303 |
+
force_download=force_download,
|
304 |
+
resume_download=resume_download,
|
305 |
+
proxies=proxies,
|
306 |
+
local_files_only=local_files_only,
|
307 |
+
use_auth_token=use_auth_token,
|
308 |
+
revision=revision,
|
309 |
+
subfolder=subfolder,
|
310 |
+
# model args
|
311 |
+
dtype=dtype,
|
312 |
+
**kwargs,
|
313 |
+
)
|
314 |
+
|
315 |
+
# Load model
|
316 |
+
pretrained_path_with_subfolder = (
|
317 |
+
pretrained_model_name_or_path
|
318 |
+
if subfolder is None
|
319 |
+
else os.path.join(pretrained_model_name_or_path, subfolder)
|
320 |
+
)
|
321 |
+
if os.path.isdir(pretrained_path_with_subfolder):
|
322 |
+
if from_pt:
|
323 |
+
if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
|
324 |
+
raise EnvironmentError(
|
325 |
+
f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} "
|
326 |
+
)
|
327 |
+
model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)
|
328 |
+
elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):
|
329 |
+
# Load from a Flax checkpoint
|
330 |
+
model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)
|
331 |
+
# Check if pytorch weights exist instead
|
332 |
+
elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
|
333 |
+
raise EnvironmentError(
|
334 |
+
f"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model"
|
335 |
+
" using `from_pt=True`."
|
336 |
+
)
|
337 |
+
else:
|
338 |
+
raise EnvironmentError(
|
339 |
+
f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
|
340 |
+
f"{pretrained_path_with_subfolder}."
|
341 |
+
)
|
342 |
+
else:
|
343 |
+
try:
|
344 |
+
model_file = hf_hub_download(
|
345 |
+
pretrained_model_name_or_path,
|
346 |
+
filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,
|
347 |
+
cache_dir=cache_dir,
|
348 |
+
force_download=force_download,
|
349 |
+
proxies=proxies,
|
350 |
+
resume_download=resume_download,
|
351 |
+
local_files_only=local_files_only,
|
352 |
+
use_auth_token=use_auth_token,
|
353 |
+
user_agent=user_agent,
|
354 |
+
subfolder=subfolder,
|
355 |
+
revision=revision,
|
356 |
+
)
|
357 |
+
|
358 |
+
except RepositoryNotFoundError:
|
359 |
+
raise EnvironmentError(
|
360 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
|
361 |
+
"listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
|
362 |
+
"token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
|
363 |
+
"login`."
|
364 |
+
)
|
365 |
+
except RevisionNotFoundError:
|
366 |
+
raise EnvironmentError(
|
367 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
|
368 |
+
"this model name. Check the model page at "
|
369 |
+
f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
370 |
+
)
|
371 |
+
except EntryNotFoundError:
|
372 |
+
raise EnvironmentError(
|
373 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}."
|
374 |
+
)
|
375 |
+
except HTTPError as err:
|
376 |
+
raise EnvironmentError(
|
377 |
+
f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
|
378 |
+
f"{err}"
|
379 |
+
)
|
380 |
+
except ValueError:
|
381 |
+
raise EnvironmentError(
|
382 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
383 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
384 |
+
f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your"
|
385 |
+
" internet connection or see how to run the library in offline mode at"
|
386 |
+
" 'https://huggingface.co/docs/transformers/installation#offline-mode'."
|
387 |
+
)
|
388 |
+
except EnvironmentError:
|
389 |
+
raise EnvironmentError(
|
390 |
+
f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
391 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
392 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
393 |
+
f"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
|
394 |
+
)
|
395 |
+
|
396 |
+
if from_pt:
|
397 |
+
if is_torch_available():
|
398 |
+
from .modeling_utils import load_state_dict
|
399 |
+
else:
|
400 |
+
raise EnvironmentError(
|
401 |
+
"Can't load the model in PyTorch format because PyTorch is not installed. "
|
402 |
+
"Please, install PyTorch or use native Flax weights."
|
403 |
+
)
|
404 |
+
|
405 |
+
# Step 1: Get the pytorch file
|
406 |
+
pytorch_model_file = load_state_dict(model_file)
|
407 |
+
|
408 |
+
# Step 2: Convert the weights
|
409 |
+
state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)
|
410 |
+
else:
|
411 |
+
try:
|
412 |
+
with open(model_file, "rb") as state_f:
|
413 |
+
state = from_bytes(cls, state_f.read())
|
414 |
+
except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
|
415 |
+
try:
|
416 |
+
with open(model_file) as f:
|
417 |
+
if f.read().startswith("version"):
|
418 |
+
raise OSError(
|
419 |
+
"You seem to have cloned a repository without having git-lfs installed. Please"
|
420 |
+
" install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
|
421 |
+
" folder you cloned."
|
422 |
+
)
|
423 |
+
else:
|
424 |
+
raise ValueError from e
|
425 |
+
except (UnicodeDecodeError, ValueError):
|
426 |
+
raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
|
427 |
+
# make sure all arrays are stored as jnp.ndarray
|
428 |
+
# NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
|
429 |
+
# https://github.com/google/flax/issues/1261
|
430 |
+
state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices("cpu")[0]), state)
|
431 |
+
|
432 |
+
# flatten dicts
|
433 |
+
state = flatten_dict(state)
|
434 |
+
|
435 |
+
params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))
|
436 |
+
required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
|
437 |
+
|
438 |
+
shape_state = flatten_dict(unfreeze(params_shape_tree))
|
439 |
+
|
440 |
+
missing_keys = required_params - set(state.keys())
|
441 |
+
unexpected_keys = set(state.keys()) - required_params
|
442 |
+
|
443 |
+
if missing_keys:
|
444 |
+
logger.warning(
|
445 |
+
f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
|
446 |
+
"Make sure to call model.init_weights to initialize the missing weights."
|
447 |
+
)
|
448 |
+
cls._missing_keys = missing_keys
|
449 |
+
|
450 |
+
for key in state.keys():
|
451 |
+
if key in shape_state and state[key].shape != shape_state[key].shape:
|
452 |
+
raise ValueError(
|
453 |
+
f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
|
454 |
+
f"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. "
|
455 |
+
)
|
456 |
+
|
457 |
+
# remove unexpected keys to not be saved again
|
458 |
+
for unexpected_key in unexpected_keys:
|
459 |
+
del state[unexpected_key]
|
460 |
+
|
461 |
+
if len(unexpected_keys) > 0:
|
462 |
+
logger.warning(
|
463 |
+
f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
|
464 |
+
f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
|
465 |
+
f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
|
466 |
+
" with another architecture."
|
467 |
+
)
|
468 |
+
else:
|
469 |
+
logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
|
470 |
+
|
471 |
+
if len(missing_keys) > 0:
|
472 |
+
logger.warning(
|
473 |
+
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
|
474 |
+
f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
|
475 |
+
" TRAIN this model on a down-stream task to be able to use it for predictions and inference."
|
476 |
+
)
|
477 |
+
else:
|
478 |
+
logger.info(
|
479 |
+
f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
|
480 |
+
f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
|
481 |
+
f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
|
482 |
+
" training."
|
483 |
+
)
|
484 |
+
|
485 |
+
return model, unflatten_dict(state)
|
486 |
+
|
487 |
+
def save_pretrained(
|
488 |
+
self,
|
489 |
+
save_directory: Union[str, os.PathLike],
|
490 |
+
params: Union[Dict, FrozenDict],
|
491 |
+
is_main_process: bool = True,
|
492 |
+
):
|
493 |
+
"""
|
494 |
+
Save a model and its configuration file to a directory, so that it can be re-loaded using the
|
495 |
+
`[`~FlaxModelMixin.from_pretrained`]` class method
|
496 |
+
|
497 |
+
Arguments:
|
498 |
+
save_directory (`str` or `os.PathLike`):
|
499 |
+
Directory to which to save. Will be created if it doesn't exist.
|
500 |
+
params (`Union[Dict, FrozenDict]`):
|
501 |
+
A `PyTree` of model parameters.
|
502 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
503 |
+
Whether the process calling this is the main process or not. Useful when in distributed training like
|
504 |
+
TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
|
505 |
+
the main process to avoid race conditions.
|
506 |
+
"""
|
507 |
+
if os.path.isfile(save_directory):
|
508 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
509 |
+
return
|
510 |
+
|
511 |
+
os.makedirs(save_directory, exist_ok=True)
|
512 |
+
|
513 |
+
model_to_save = self
|
514 |
+
|
515 |
+
# Attach architecture to the config
|
516 |
+
# Save the config
|
517 |
+
if is_main_process:
|
518 |
+
model_to_save.save_config(save_directory)
|
519 |
+
|
520 |
+
# save model
|
521 |
+
output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)
|
522 |
+
with open(output_model_file, "wb") as f:
|
523 |
+
model_bytes = to_bytes(params)
|
524 |
+
f.write(model_bytes)
|
525 |
+
|
526 |
+
logger.info(f"Model weights saved in {output_model_file}")
|
diffusers/modeling_utils.py
ADDED
@@ -0,0 +1,764 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
|
17 |
+
import os
|
18 |
+
from functools import partial
|
19 |
+
from typing import Callable, List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
from torch import Tensor, device
|
23 |
+
|
24 |
+
from huggingface_hub import hf_hub_download
|
25 |
+
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
|
26 |
+
from requests import HTTPError
|
27 |
+
|
28 |
+
from . import __version__
|
29 |
+
from .utils import (
|
30 |
+
CONFIG_NAME,
|
31 |
+
DIFFUSERS_CACHE,
|
32 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
33 |
+
SAFETENSORS_WEIGHTS_NAME,
|
34 |
+
WEIGHTS_NAME,
|
35 |
+
is_accelerate_available,
|
36 |
+
is_safetensors_available,
|
37 |
+
is_torch_version,
|
38 |
+
logging,
|
39 |
+
)
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
|
45 |
+
if is_torch_version(">=", "1.9.0"):
|
46 |
+
_LOW_CPU_MEM_USAGE_DEFAULT = True
|
47 |
+
else:
|
48 |
+
_LOW_CPU_MEM_USAGE_DEFAULT = False
|
49 |
+
|
50 |
+
|
51 |
+
if is_accelerate_available():
|
52 |
+
import accelerate
|
53 |
+
from accelerate.utils import set_module_tensor_to_device
|
54 |
+
from accelerate.utils.versions import is_torch_version
|
55 |
+
|
56 |
+
if is_safetensors_available():
|
57 |
+
import safetensors
|
58 |
+
|
59 |
+
|
60 |
+
def get_parameter_device(parameter: torch.nn.Module):
|
61 |
+
try:
|
62 |
+
return next(parameter.parameters()).device
|
63 |
+
except StopIteration:
|
64 |
+
# For torch.nn.DataParallel compatibility in PyTorch 1.5
|
65 |
+
|
66 |
+
def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
|
67 |
+
tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
|
68 |
+
return tuples
|
69 |
+
|
70 |
+
gen = parameter._named_members(get_members_fn=find_tensor_attributes)
|
71 |
+
first_tuple = next(gen)
|
72 |
+
return first_tuple[1].device
|
73 |
+
|
74 |
+
|
75 |
+
def get_parameter_dtype(parameter: torch.nn.Module):
|
76 |
+
try:
|
77 |
+
return next(parameter.parameters()).dtype
|
78 |
+
except StopIteration:
|
79 |
+
# For torch.nn.DataParallel compatibility in PyTorch 1.5
|
80 |
+
|
81 |
+
def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
|
82 |
+
tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
|
83 |
+
return tuples
|
84 |
+
|
85 |
+
gen = parameter._named_members(get_members_fn=find_tensor_attributes)
|
86 |
+
first_tuple = next(gen)
|
87 |
+
return first_tuple[1].dtype
|
88 |
+
|
89 |
+
|
90 |
+
def load_state_dict(checkpoint_file: Union[str, os.PathLike]):
|
91 |
+
"""
|
92 |
+
Reads a checkpoint file, returning properly formatted errors if they arise.
|
93 |
+
"""
|
94 |
+
try:
|
95 |
+
if os.path.basename(checkpoint_file) == WEIGHTS_NAME:
|
96 |
+
return torch.load(checkpoint_file, map_location="cpu")
|
97 |
+
else:
|
98 |
+
return safetensors.torch.load_file(checkpoint_file, device="cpu")
|
99 |
+
except Exception as e:
|
100 |
+
try:
|
101 |
+
with open(checkpoint_file) as f:
|
102 |
+
if f.read().startswith("version"):
|
103 |
+
raise OSError(
|
104 |
+
"You seem to have cloned a repository without having git-lfs installed. Please install "
|
105 |
+
"git-lfs and run `git lfs install` followed by `git lfs pull` in the folder "
|
106 |
+
"you cloned."
|
107 |
+
)
|
108 |
+
else:
|
109 |
+
raise ValueError(
|
110 |
+
f"Unable to locate the file {checkpoint_file} which is necessary to load this pretrained "
|
111 |
+
"model. Make sure you have saved the model properly."
|
112 |
+
) from e
|
113 |
+
except (UnicodeDecodeError, ValueError):
|
114 |
+
raise OSError(
|
115 |
+
f"Unable to load weights from checkpoint file for '{checkpoint_file}' "
|
116 |
+
f"at '{checkpoint_file}'. "
|
117 |
+
"If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True."
|
118 |
+
)
|
119 |
+
|
120 |
+
|
121 |
+
def _load_state_dict_into_model(model_to_load, state_dict):
|
122 |
+
# Convert old format to new format if needed from a PyTorch state_dict
|
123 |
+
# copy state_dict so _load_from_state_dict can modify it
|
124 |
+
state_dict = state_dict.copy()
|
125 |
+
error_msgs = []
|
126 |
+
|
127 |
+
# PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
|
128 |
+
# so we need to apply the function recursively.
|
129 |
+
def load(module: torch.nn.Module, prefix=""):
|
130 |
+
args = (state_dict, prefix, {}, True, [], [], error_msgs)
|
131 |
+
module._load_from_state_dict(*args)
|
132 |
+
|
133 |
+
for name, child in module._modules.items():
|
134 |
+
if child is not None:
|
135 |
+
load(child, prefix + name + ".")
|
136 |
+
|
137 |
+
load(model_to_load)
|
138 |
+
|
139 |
+
return error_msgs
|
140 |
+
|
141 |
+
|
142 |
+
class ModelMixin(torch.nn.Module):
|
143 |
+
r"""
|
144 |
+
Base class for all models.
|
145 |
+
|
146 |
+
[`ModelMixin`] takes care of storing the configuration of the models and handles methods for loading, downloading
|
147 |
+
and saving models.
|
148 |
+
|
149 |
+
- **config_name** ([`str`]) -- A filename under which the model should be stored when calling
|
150 |
+
[`~modeling_utils.ModelMixin.save_pretrained`].
|
151 |
+
"""
|
152 |
+
config_name = CONFIG_NAME
|
153 |
+
_automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
|
154 |
+
_supports_gradient_checkpointing = False
|
155 |
+
|
156 |
+
def __init__(self):
|
157 |
+
super().__init__()
|
158 |
+
|
159 |
+
@property
|
160 |
+
def is_gradient_checkpointing(self) -> bool:
|
161 |
+
"""
|
162 |
+
Whether gradient checkpointing is activated for this model or not.
|
163 |
+
|
164 |
+
Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint
|
165 |
+
activations".
|
166 |
+
"""
|
167 |
+
return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())
|
168 |
+
|
169 |
+
def enable_gradient_checkpointing(self):
|
170 |
+
"""
|
171 |
+
Activates gradient checkpointing for the current model.
|
172 |
+
|
173 |
+
Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint
|
174 |
+
activations".
|
175 |
+
"""
|
176 |
+
if not self._supports_gradient_checkpointing:
|
177 |
+
raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
|
178 |
+
self.apply(partial(self._set_gradient_checkpointing, value=True))
|
179 |
+
|
180 |
+
def disable_gradient_checkpointing(self):
|
181 |
+
"""
|
182 |
+
Deactivates gradient checkpointing for the current model.
|
183 |
+
|
184 |
+
Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint
|
185 |
+
activations".
|
186 |
+
"""
|
187 |
+
if self._supports_gradient_checkpointing:
|
188 |
+
self.apply(partial(self._set_gradient_checkpointing, value=False))
|
189 |
+
|
190 |
+
def save_pretrained(
|
191 |
+
self,
|
192 |
+
save_directory: Union[str, os.PathLike],
|
193 |
+
is_main_process: bool = True,
|
194 |
+
save_function: Callable = None,
|
195 |
+
safe_serialization: bool = False,
|
196 |
+
):
|
197 |
+
"""
|
198 |
+
Save a model and its configuration file to a directory, so that it can be re-loaded using the
|
199 |
+
`[`~modeling_utils.ModelMixin.from_pretrained`]` class method.
|
200 |
+
|
201 |
+
Arguments:
|
202 |
+
save_directory (`str` or `os.PathLike`):
|
203 |
+
Directory to which to save. Will be created if it doesn't exist.
|
204 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
205 |
+
Whether the process calling this is the main process or not. Useful when in distributed training like
|
206 |
+
TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
|
207 |
+
the main process to avoid race conditions.
|
208 |
+
save_function (`Callable`):
|
209 |
+
The function to use to save the state dictionary. Useful on distributed training like TPUs when one
|
210 |
+
need to replace `torch.save` by another method. Can be configured with the environment variable
|
211 |
+
`DIFFUSERS_SAVE_MODE`.
|
212 |
+
safe_serialization (`bool`, *optional*, defaults to `False`):
|
213 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
214 |
+
"""
|
215 |
+
if safe_serialization and not is_safetensors_available():
|
216 |
+
raise ImportError("`safe_serialization` requires the `safetensors library: `pip install safetensors`.")
|
217 |
+
|
218 |
+
if os.path.isfile(save_directory):
|
219 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
220 |
+
return
|
221 |
+
|
222 |
+
if save_function is None:
|
223 |
+
save_function = safetensors.torch.save_file if safe_serialization else torch.save
|
224 |
+
|
225 |
+
os.makedirs(save_directory, exist_ok=True)
|
226 |
+
|
227 |
+
model_to_save = self
|
228 |
+
|
229 |
+
# Attach architecture to the config
|
230 |
+
# Save the config
|
231 |
+
if is_main_process:
|
232 |
+
model_to_save.save_config(save_directory)
|
233 |
+
|
234 |
+
# Save the model
|
235 |
+
state_dict = model_to_save.state_dict()
|
236 |
+
|
237 |
+
weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
|
238 |
+
|
239 |
+
# Clean the folder from a previous save
|
240 |
+
for filename in os.listdir(save_directory):
|
241 |
+
full_filename = os.path.join(save_directory, filename)
|
242 |
+
# If we have a shard file that is not going to be replaced, we delete it, but only from the main process
|
243 |
+
# in distributed settings to avoid race conditions.
|
244 |
+
weights_no_suffix = weights_name.replace(".bin", "").replace(".safetensors", "")
|
245 |
+
if filename.startswith(weights_no_suffix) and os.path.isfile(full_filename) and is_main_process:
|
246 |
+
os.remove(full_filename)
|
247 |
+
|
248 |
+
# Save the model
|
249 |
+
save_function(state_dict, os.path.join(save_directory, weights_name))
|
250 |
+
|
251 |
+
logger.info(f"Model weights saved in {os.path.join(save_directory, weights_name)}")
|
252 |
+
|
253 |
+
@classmethod
|
254 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
|
255 |
+
r"""
|
256 |
+
Instantiate a pretrained pytorch model from a pre-trained model configuration.
|
257 |
+
|
258 |
+
The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
|
259 |
+
the model, you should first set it back in training mode with `model.train()`.
|
260 |
+
|
261 |
+
The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
|
262 |
+
pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
|
263 |
+
task.
|
264 |
+
|
265 |
+
The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
|
266 |
+
weights are discarded.
|
267 |
+
|
268 |
+
Parameters:
|
269 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
270 |
+
Can be either:
|
271 |
+
|
272 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
273 |
+
Valid model ids should have an organization name, like `google/ddpm-celebahq-256`.
|
274 |
+
- A path to a *directory* containing model weights saved using [`~ModelMixin.save_config`], e.g.,
|
275 |
+
`./my_model_directory/`.
|
276 |
+
|
277 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
278 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
279 |
+
standard cache should not be used.
|
280 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
281 |
+
Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
|
282 |
+
will be automatically derived from the model's weights.
|
283 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
284 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
285 |
+
cached versions if they exist.
|
286 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
287 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
288 |
+
file exists.
|
289 |
+
proxies (`Dict[str, str]`, *optional*):
|
290 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
291 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
292 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
293 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
294 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
295 |
+
Whether or not to only look at local files (i.e., do not try to download the model).
|
296 |
+
use_auth_token (`str` or *bool*, *optional*):
|
297 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
298 |
+
when running `diffusers-cli login` (stored in `~/.huggingface`).
|
299 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
300 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
301 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
302 |
+
identifier allowed by git.
|
303 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
304 |
+
In case the relevant files are located inside a subfolder of the model repo (either remote in
|
305 |
+
huggingface.co or downloaded locally), you can specify the folder name here.
|
306 |
+
|
307 |
+
mirror (`str`, *optional*):
|
308 |
+
Mirror source to accelerate downloads in China. If you are from China and have an accessibility
|
309 |
+
problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
|
310 |
+
Please refer to the mirror site for more information.
|
311 |
+
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
312 |
+
A map that specifies where each submodule should go. It doesn't need to be refined to each
|
313 |
+
parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
|
314 |
+
same device.
|
315 |
+
|
316 |
+
To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
|
317 |
+
more information about each option see [designing a device
|
318 |
+
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
|
319 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
320 |
+
Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
|
321 |
+
also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
|
322 |
+
model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
|
323 |
+
setting this argument to `True` will raise an error.
|
324 |
+
|
325 |
+
<Tip>
|
326 |
+
|
327 |
+
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
|
328 |
+
models](https://huggingface.co/docs/hub/models-gated#gated-models).
|
329 |
+
|
330 |
+
</Tip>
|
331 |
+
|
332 |
+
<Tip>
|
333 |
+
|
334 |
+
Activate the special ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use
|
335 |
+
this method in a firewalled environment.
|
336 |
+
|
337 |
+
</Tip>
|
338 |
+
|
339 |
+
"""
|
340 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
341 |
+
ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
|
342 |
+
force_download = kwargs.pop("force_download", False)
|
343 |
+
resume_download = kwargs.pop("resume_download", False)
|
344 |
+
proxies = kwargs.pop("proxies", None)
|
345 |
+
output_loading_info = kwargs.pop("output_loading_info", False)
|
346 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
347 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
348 |
+
revision = kwargs.pop("revision", None)
|
349 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
350 |
+
subfolder = kwargs.pop("subfolder", None)
|
351 |
+
device_map = kwargs.pop("device_map", None)
|
352 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
353 |
+
|
354 |
+
if low_cpu_mem_usage and not is_accelerate_available():
|
355 |
+
low_cpu_mem_usage = False
|
356 |
+
logger.warning(
|
357 |
+
"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
|
358 |
+
" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
|
359 |
+
" `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
|
360 |
+
" install accelerate\n```\n."
|
361 |
+
)
|
362 |
+
|
363 |
+
if device_map is not None and not is_accelerate_available():
|
364 |
+
raise NotImplementedError(
|
365 |
+
"Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set"
|
366 |
+
" `device_map=None`. You can install accelerate with `pip install accelerate`."
|
367 |
+
)
|
368 |
+
|
369 |
+
# Check if we can handle device_map and dispatching the weights
|
370 |
+
if device_map is not None and not is_torch_version(">=", "1.9.0"):
|
371 |
+
raise NotImplementedError(
|
372 |
+
"Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
|
373 |
+
" `device_map=None`."
|
374 |
+
)
|
375 |
+
|
376 |
+
if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
|
377 |
+
raise NotImplementedError(
|
378 |
+
"Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
|
379 |
+
" `low_cpu_mem_usage=False`."
|
380 |
+
)
|
381 |
+
|
382 |
+
if low_cpu_mem_usage is False and device_map is not None:
|
383 |
+
raise ValueError(
|
384 |
+
f"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and"
|
385 |
+
" dispatching. Please make sure to set `low_cpu_mem_usage=True`."
|
386 |
+
)
|
387 |
+
|
388 |
+
user_agent = {
|
389 |
+
"diffusers": __version__,
|
390 |
+
"file_type": "model",
|
391 |
+
"framework": "pytorch",
|
392 |
+
}
|
393 |
+
|
394 |
+
# Load config if we don't provide a configuration
|
395 |
+
config_path = pretrained_model_name_or_path
|
396 |
+
|
397 |
+
# This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the
|
398 |
+
# Load model
|
399 |
+
|
400 |
+
model_file = None
|
401 |
+
if is_safetensors_available():
|
402 |
+
try:
|
403 |
+
model_file = _get_model_file(
|
404 |
+
pretrained_model_name_or_path,
|
405 |
+
weights_name=SAFETENSORS_WEIGHTS_NAME,
|
406 |
+
cache_dir=cache_dir,
|
407 |
+
force_download=force_download,
|
408 |
+
resume_download=resume_download,
|
409 |
+
proxies=proxies,
|
410 |
+
local_files_only=local_files_only,
|
411 |
+
use_auth_token=use_auth_token,
|
412 |
+
revision=revision,
|
413 |
+
subfolder=subfolder,
|
414 |
+
user_agent=user_agent,
|
415 |
+
)
|
416 |
+
except:
|
417 |
+
pass
|
418 |
+
if model_file is None:
|
419 |
+
model_file = _get_model_file(
|
420 |
+
pretrained_model_name_or_path,
|
421 |
+
weights_name=WEIGHTS_NAME,
|
422 |
+
cache_dir=cache_dir,
|
423 |
+
force_download=force_download,
|
424 |
+
resume_download=resume_download,
|
425 |
+
proxies=proxies,
|
426 |
+
local_files_only=local_files_only,
|
427 |
+
use_auth_token=use_auth_token,
|
428 |
+
revision=revision,
|
429 |
+
subfolder=subfolder,
|
430 |
+
user_agent=user_agent,
|
431 |
+
)
|
432 |
+
|
433 |
+
if low_cpu_mem_usage:
|
434 |
+
# Instantiate model with empty weights
|
435 |
+
with accelerate.init_empty_weights():
|
436 |
+
config, unused_kwargs = cls.load_config(
|
437 |
+
config_path,
|
438 |
+
cache_dir=cache_dir,
|
439 |
+
return_unused_kwargs=True,
|
440 |
+
force_download=force_download,
|
441 |
+
resume_download=resume_download,
|
442 |
+
proxies=proxies,
|
443 |
+
local_files_only=local_files_only,
|
444 |
+
use_auth_token=use_auth_token,
|
445 |
+
revision=revision,
|
446 |
+
subfolder=subfolder,
|
447 |
+
device_map=device_map,
|
448 |
+
**kwargs,
|
449 |
+
)
|
450 |
+
model = cls.from_config(config, **unused_kwargs)
|
451 |
+
|
452 |
+
# if device_map is Non,e load the state dict on move the params from meta device to the cpu
|
453 |
+
if device_map is None:
|
454 |
+
param_device = "cpu"
|
455 |
+
state_dict = load_state_dict(model_file)
|
456 |
+
# move the parms from meta device to cpu
|
457 |
+
for param_name, param in state_dict.items():
|
458 |
+
set_module_tensor_to_device(model, param_name, param_device, value=param)
|
459 |
+
else: # else let accelerate handle loading and dispatching.
|
460 |
+
# Load weights and dispatch according to the device_map
|
461 |
+
# by deafult the device_map is None and the weights are loaded on the CPU
|
462 |
+
accelerate.load_checkpoint_and_dispatch(model, model_file, device_map)
|
463 |
+
|
464 |
+
loading_info = {
|
465 |
+
"missing_keys": [],
|
466 |
+
"unexpected_keys": [],
|
467 |
+
"mismatched_keys": [],
|
468 |
+
"error_msgs": [],
|
469 |
+
}
|
470 |
+
else:
|
471 |
+
config, unused_kwargs = cls.load_config(
|
472 |
+
config_path,
|
473 |
+
cache_dir=cache_dir,
|
474 |
+
return_unused_kwargs=True,
|
475 |
+
force_download=force_download,
|
476 |
+
resume_download=resume_download,
|
477 |
+
proxies=proxies,
|
478 |
+
local_files_only=local_files_only,
|
479 |
+
use_auth_token=use_auth_token,
|
480 |
+
revision=revision,
|
481 |
+
subfolder=subfolder,
|
482 |
+
device_map=device_map,
|
483 |
+
**kwargs,
|
484 |
+
)
|
485 |
+
model = cls.from_config(config, **unused_kwargs)
|
486 |
+
|
487 |
+
state_dict = load_state_dict(model_file)
|
488 |
+
dtype = set(v.dtype for v in state_dict.values())
|
489 |
+
|
490 |
+
if len(dtype) > 1 and torch.float32 not in dtype:
|
491 |
+
raise ValueError(
|
492 |
+
f"The weights of the model file {model_file} have a mixture of incompatible dtypes {dtype}. Please"
|
493 |
+
f" make sure that {model_file} weights have only one dtype."
|
494 |
+
)
|
495 |
+
elif len(dtype) > 1 and torch.float32 in dtype:
|
496 |
+
dtype = torch.float32
|
497 |
+
else:
|
498 |
+
dtype = dtype.pop()
|
499 |
+
|
500 |
+
# move model to correct dtype
|
501 |
+
model = model.to(dtype)
|
502 |
+
|
503 |
+
model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_pretrained_model(
|
504 |
+
model,
|
505 |
+
state_dict,
|
506 |
+
model_file,
|
507 |
+
pretrained_model_name_or_path,
|
508 |
+
ignore_mismatched_sizes=ignore_mismatched_sizes,
|
509 |
+
)
|
510 |
+
|
511 |
+
loading_info = {
|
512 |
+
"missing_keys": missing_keys,
|
513 |
+
"unexpected_keys": unexpected_keys,
|
514 |
+
"mismatched_keys": mismatched_keys,
|
515 |
+
"error_msgs": error_msgs,
|
516 |
+
}
|
517 |
+
|
518 |
+
if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):
|
519 |
+
raise ValueError(
|
520 |
+
f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."
|
521 |
+
)
|
522 |
+
elif torch_dtype is not None:
|
523 |
+
model = model.to(torch_dtype)
|
524 |
+
|
525 |
+
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
|
526 |
+
|
527 |
+
# Set model in evaluation mode to deactivate DropOut modules by default
|
528 |
+
model.eval()
|
529 |
+
if output_loading_info:
|
530 |
+
return model, loading_info
|
531 |
+
|
532 |
+
return model
|
533 |
+
|
534 |
+
@classmethod
|
535 |
+
def _load_pretrained_model(
|
536 |
+
cls,
|
537 |
+
model,
|
538 |
+
state_dict,
|
539 |
+
resolved_archive_file,
|
540 |
+
pretrained_model_name_or_path,
|
541 |
+
ignore_mismatched_sizes=False,
|
542 |
+
):
|
543 |
+
# Retrieve missing & unexpected_keys
|
544 |
+
model_state_dict = model.state_dict()
|
545 |
+
loaded_keys = [k for k in state_dict.keys()]
|
546 |
+
|
547 |
+
expected_keys = list(model_state_dict.keys())
|
548 |
+
|
549 |
+
original_loaded_keys = loaded_keys
|
550 |
+
|
551 |
+
missing_keys = list(set(expected_keys) - set(loaded_keys))
|
552 |
+
unexpected_keys = list(set(loaded_keys) - set(expected_keys))
|
553 |
+
|
554 |
+
# Make sure we are able to load base models as well as derived models (with heads)
|
555 |
+
model_to_load = model
|
556 |
+
|
557 |
+
def _find_mismatched_keys(
|
558 |
+
state_dict,
|
559 |
+
model_state_dict,
|
560 |
+
loaded_keys,
|
561 |
+
ignore_mismatched_sizes,
|
562 |
+
):
|
563 |
+
mismatched_keys = []
|
564 |
+
if ignore_mismatched_sizes:
|
565 |
+
for checkpoint_key in loaded_keys:
|
566 |
+
model_key = checkpoint_key
|
567 |
+
|
568 |
+
if (
|
569 |
+
model_key in model_state_dict
|
570 |
+
and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape
|
571 |
+
):
|
572 |
+
mismatched_keys.append(
|
573 |
+
(checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)
|
574 |
+
)
|
575 |
+
del state_dict[checkpoint_key]
|
576 |
+
return mismatched_keys
|
577 |
+
|
578 |
+
if state_dict is not None:
|
579 |
+
# Whole checkpoint
|
580 |
+
mismatched_keys = _find_mismatched_keys(
|
581 |
+
state_dict,
|
582 |
+
model_state_dict,
|
583 |
+
original_loaded_keys,
|
584 |
+
ignore_mismatched_sizes,
|
585 |
+
)
|
586 |
+
error_msgs = _load_state_dict_into_model(model_to_load, state_dict)
|
587 |
+
|
588 |
+
if len(error_msgs) > 0:
|
589 |
+
error_msg = "\n\t".join(error_msgs)
|
590 |
+
if "size mismatch" in error_msg:
|
591 |
+
error_msg += (
|
592 |
+
"\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
|
593 |
+
)
|
594 |
+
raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
|
595 |
+
|
596 |
+
if len(unexpected_keys) > 0:
|
597 |
+
logger.warning(
|
598 |
+
f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
|
599 |
+
f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
|
600 |
+
f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task"
|
601 |
+
" or with another architecture (e.g. initializing a BertForSequenceClassification model from a"
|
602 |
+
" BertForPreTraining model).\n- This IS NOT expected if you are initializing"
|
603 |
+
f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly"
|
604 |
+
" identical (initializing a BertForSequenceClassification model from a"
|
605 |
+
" BertForSequenceClassification model)."
|
606 |
+
)
|
607 |
+
else:
|
608 |
+
logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
|
609 |
+
if len(missing_keys) > 0:
|
610 |
+
logger.warning(
|
611 |
+
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
|
612 |
+
f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
|
613 |
+
" TRAIN this model on a down-stream task to be able to use it for predictions and inference."
|
614 |
+
)
|
615 |
+
elif len(mismatched_keys) == 0:
|
616 |
+
logger.info(
|
617 |
+
f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
|
618 |
+
f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the"
|
619 |
+
f" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions"
|
620 |
+
" without further training."
|
621 |
+
)
|
622 |
+
if len(mismatched_keys) > 0:
|
623 |
+
mismatched_warning = "\n".join(
|
624 |
+
[
|
625 |
+
f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
|
626 |
+
for key, shape1, shape2 in mismatched_keys
|
627 |
+
]
|
628 |
+
)
|
629 |
+
logger.warning(
|
630 |
+
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
|
631 |
+
f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
|
632 |
+
f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be"
|
633 |
+
" able to use it for predictions and inference."
|
634 |
+
)
|
635 |
+
|
636 |
+
return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs
|
637 |
+
|
638 |
+
@property
|
639 |
+
def device(self) -> device:
|
640 |
+
"""
|
641 |
+
`torch.device`: The device on which the module is (assuming that all the module parameters are on the same
|
642 |
+
device).
|
643 |
+
"""
|
644 |
+
return get_parameter_device(self)
|
645 |
+
|
646 |
+
@property
|
647 |
+
def dtype(self) -> torch.dtype:
|
648 |
+
"""
|
649 |
+
`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
|
650 |
+
"""
|
651 |
+
return get_parameter_dtype(self)
|
652 |
+
|
653 |
+
def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:
|
654 |
+
"""
|
655 |
+
Get number of (optionally, trainable or non-embeddings) parameters in the module.
|
656 |
+
|
657 |
+
Args:
|
658 |
+
only_trainable (`bool`, *optional*, defaults to `False`):
|
659 |
+
Whether or not to return only the number of trainable parameters
|
660 |
+
|
661 |
+
exclude_embeddings (`bool`, *optional*, defaults to `False`):
|
662 |
+
Whether or not to return only the number of non-embeddings parameters
|
663 |
+
|
664 |
+
Returns:
|
665 |
+
`int`: The number of parameters.
|
666 |
+
"""
|
667 |
+
|
668 |
+
if exclude_embeddings:
|
669 |
+
embedding_param_names = [
|
670 |
+
f"{name}.weight"
|
671 |
+
for name, module_type in self.named_modules()
|
672 |
+
if isinstance(module_type, torch.nn.Embedding)
|
673 |
+
]
|
674 |
+
non_embedding_parameters = [
|
675 |
+
parameter for name, parameter in self.named_parameters() if name not in embedding_param_names
|
676 |
+
]
|
677 |
+
return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)
|
678 |
+
else:
|
679 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)
|
680 |
+
|
681 |
+
|
682 |
+
def _get_model_file(
|
683 |
+
pretrained_model_name_or_path,
|
684 |
+
*,
|
685 |
+
weights_name,
|
686 |
+
subfolder,
|
687 |
+
cache_dir,
|
688 |
+
force_download,
|
689 |
+
proxies,
|
690 |
+
resume_download,
|
691 |
+
local_files_only,
|
692 |
+
use_auth_token,
|
693 |
+
user_agent,
|
694 |
+
revision,
|
695 |
+
):
|
696 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
697 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
698 |
+
if os.path.isfile(os.path.join(pretrained_model_name_or_path, weights_name)):
|
699 |
+
# Load from a PyTorch checkpoint
|
700 |
+
model_file = os.path.join(pretrained_model_name_or_path, weights_name)
|
701 |
+
return model_file
|
702 |
+
elif subfolder is not None and os.path.isfile(
|
703 |
+
os.path.join(pretrained_model_name_or_path, subfolder, weights_name)
|
704 |
+
):
|
705 |
+
model_file = os.path.join(pretrained_model_name_or_path, subfolder, weights_name)
|
706 |
+
return model_file
|
707 |
+
else:
|
708 |
+
raise EnvironmentError(
|
709 |
+
f"Error no file named {weights_name} found in directory {pretrained_model_name_or_path}."
|
710 |
+
)
|
711 |
+
else:
|
712 |
+
try:
|
713 |
+
# Load from URL or cache if already cached
|
714 |
+
model_file = hf_hub_download(
|
715 |
+
pretrained_model_name_or_path,
|
716 |
+
filename=weights_name,
|
717 |
+
cache_dir=cache_dir,
|
718 |
+
force_download=force_download,
|
719 |
+
proxies=proxies,
|
720 |
+
resume_download=resume_download,
|
721 |
+
local_files_only=local_files_only,
|
722 |
+
use_auth_token=use_auth_token,
|
723 |
+
user_agent=user_agent,
|
724 |
+
subfolder=subfolder,
|
725 |
+
revision=revision,
|
726 |
+
)
|
727 |
+
return model_file
|
728 |
+
|
729 |
+
except RepositoryNotFoundError:
|
730 |
+
raise EnvironmentError(
|
731 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
|
732 |
+
"listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
|
733 |
+
"token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
|
734 |
+
"login`."
|
735 |
+
)
|
736 |
+
except RevisionNotFoundError:
|
737 |
+
raise EnvironmentError(
|
738 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
|
739 |
+
"this model name. Check the model page at "
|
740 |
+
f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
741 |
+
)
|
742 |
+
except EntryNotFoundError:
|
743 |
+
raise EnvironmentError(
|
744 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {weights_name}."
|
745 |
+
)
|
746 |
+
except HTTPError as err:
|
747 |
+
raise EnvironmentError(
|
748 |
+
f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}"
|
749 |
+
)
|
750 |
+
except ValueError:
|
751 |
+
raise EnvironmentError(
|
752 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
753 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
754 |
+
f" directory containing a file named {weights_name} or"
|
755 |
+
" \nCheckout your internet connection or see how to run the library in"
|
756 |
+
" offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
|
757 |
+
)
|
758 |
+
except EnvironmentError:
|
759 |
+
raise EnvironmentError(
|
760 |
+
f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
761 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
762 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
763 |
+
f"containing a file named {weights_name}"
|
764 |
+
)
|
diffusers/models/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# Models
|
2 |
+
|
3 |
+
For more detail on the models, please refer to the [docs](https://huggingface.co/docs/diffusers/api/models).
|