autoregressive-diffusion-pytorch 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- autoregressive_diffusion_pytorch-0.0.1/.github/workflows/python-publish.yml +36 -0
- autoregressive_diffusion_pytorch-0.0.1/.gitignore +162 -0
- autoregressive_diffusion_pytorch-0.0.1/LICENSE +21 -0
- autoregressive_diffusion_pytorch-0.0.1/PKG-INFO +94 -0
- autoregressive_diffusion_pytorch-0.0.1/README.md +48 -0
- autoregressive_diffusion_pytorch-0.0.1/ar-diffusion.png +0 -0
- autoregressive_diffusion_pytorch-0.0.1/autoregressive_diffusion_pytorch/__init__.py +4 -0
- autoregressive_diffusion_pytorch-0.0.1/autoregressive_diffusion_pytorch/autoregressive_diffusion.py +474 -0
- autoregressive_diffusion_pytorch-0.0.1/pyproject.toml +48 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# This workflow will upload a Python Package using Twine when a release is created
|
|
2
|
+
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
|
|
3
|
+
|
|
4
|
+
# This workflow uses actions that are not certified by GitHub.
|
|
5
|
+
# They are provided by a third-party and are governed by
|
|
6
|
+
# separate terms of service, privacy policy, and support
|
|
7
|
+
# documentation.
|
|
8
|
+
|
|
9
|
+
name: Upload Python Package
|
|
10
|
+
|
|
11
|
+
on:
|
|
12
|
+
release:
|
|
13
|
+
types: [published]
|
|
14
|
+
|
|
15
|
+
jobs:
|
|
16
|
+
deploy:
|
|
17
|
+
|
|
18
|
+
runs-on: ubuntu-latest
|
|
19
|
+
|
|
20
|
+
steps:
|
|
21
|
+
- uses: actions/checkout@v2
|
|
22
|
+
- name: Set up Python
|
|
23
|
+
uses: actions/setup-python@v2
|
|
24
|
+
with:
|
|
25
|
+
python-version: '3.x'
|
|
26
|
+
- name: Install dependencies
|
|
27
|
+
run: |
|
|
28
|
+
python -m pip install --upgrade pip
|
|
29
|
+
pip install build
|
|
30
|
+
- name: Build package
|
|
31
|
+
run: python -m build
|
|
32
|
+
- name: Publish package
|
|
33
|
+
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
|
|
34
|
+
with:
|
|
35
|
+
user: __token__
|
|
36
|
+
password: ${{ secrets.PYPI_API_TOKEN }}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py,cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# poetry
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
102
|
+
#poetry.lock
|
|
103
|
+
|
|
104
|
+
# pdm
|
|
105
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
106
|
+
#pdm.lock
|
|
107
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
108
|
+
# in version control.
|
|
109
|
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
110
|
+
.pdm.toml
|
|
111
|
+
.pdm-python
|
|
112
|
+
.pdm-build/
|
|
113
|
+
|
|
114
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
115
|
+
__pypackages__/
|
|
116
|
+
|
|
117
|
+
# Celery stuff
|
|
118
|
+
celerybeat-schedule
|
|
119
|
+
celerybeat.pid
|
|
120
|
+
|
|
121
|
+
# SageMath parsed files
|
|
122
|
+
*.sage.py
|
|
123
|
+
|
|
124
|
+
# Environments
|
|
125
|
+
.env
|
|
126
|
+
.venv
|
|
127
|
+
env/
|
|
128
|
+
venv/
|
|
129
|
+
ENV/
|
|
130
|
+
env.bak/
|
|
131
|
+
venv.bak/
|
|
132
|
+
|
|
133
|
+
# Spyder project settings
|
|
134
|
+
.spyderproject
|
|
135
|
+
.spyproject
|
|
136
|
+
|
|
137
|
+
# Rope project settings
|
|
138
|
+
.ropeproject
|
|
139
|
+
|
|
140
|
+
# mkdocs documentation
|
|
141
|
+
/site
|
|
142
|
+
|
|
143
|
+
# mypy
|
|
144
|
+
.mypy_cache/
|
|
145
|
+
.dmypy.json
|
|
146
|
+
dmypy.json
|
|
147
|
+
|
|
148
|
+
# Pyre type checker
|
|
149
|
+
.pyre/
|
|
150
|
+
|
|
151
|
+
# pytype static type analyzer
|
|
152
|
+
.pytype/
|
|
153
|
+
|
|
154
|
+
# Cython debug symbols
|
|
155
|
+
cython_debug/
|
|
156
|
+
|
|
157
|
+
# PyCharm
|
|
158
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
159
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
160
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
161
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
162
|
+
#.idea/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Phil Wang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: autoregressive-diffusion-pytorch
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Autoregressive Diffusion - Pytorch
|
|
5
|
+
Project-URL: Homepage, https://pypi.org/project/autoregressive-diffusion-pytorch/
|
|
6
|
+
Project-URL: Repository, https://github.com/lucidrains/autoregressive-diffusion-pytorch
|
|
7
|
+
Author-email: Phil Wang <lucidrains@gmail.com>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2024 Phil Wang
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: artificial intelligence,deep learning,denoising diffusion,transformers
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
35
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
36
|
+
Requires-Python: >=3.8
|
|
37
|
+
Requires-Dist: einops>=0.8.0
|
|
38
|
+
Requires-Dist: einx>=0.3.0
|
|
39
|
+
Requires-Dist: torch>=2.0
|
|
40
|
+
Requires-Dist: tqdm
|
|
41
|
+
Requires-Dist: x-transformers>=1.31.14
|
|
42
|
+
Provides-Extra: examples
|
|
43
|
+
Requires-Dist: numpy; extra == 'examples'
|
|
44
|
+
Requires-Dist: tqdm; extra == 'examples'
|
|
45
|
+
Description-Content-Type: text/markdown
|
|
46
|
+
|
|
47
|
+
<img src="./ar-diffusion.png" width="400px"></img>
|
|
48
|
+
|
|
49
|
+
## Autoregressive Diffusion - Pytorch (wip)
|
|
50
|
+
|
|
51
|
+
Implementation of the architecture behind <a href="https://arxiv.org/abs/2406.11838">Autoregressive Image Generation without Vector Quantization</a> in Pytorch
|
|
52
|
+
|
|
53
|
+
You can discuss the paper temporarily [here](https://discord.com/invite/9myQVTbN)
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
$ pip install autoregressive-diffusion-pytorch
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import torch
|
|
65
|
+
from autoregressive_diffusion_pytorch import AutoregressiveDiffusion
|
|
66
|
+
|
|
67
|
+
model = AutoregressiveDiffusion(
|
|
68
|
+
dim = 512,
|
|
69
|
+
max_seq_len = 32
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
seq = torch.randn(3, 32, 512)
|
|
73
|
+
|
|
74
|
+
loss = model(seq)
|
|
75
|
+
loss.backward()
|
|
76
|
+
|
|
77
|
+
sampled = model.sample(batch_size = 3)
|
|
78
|
+
|
|
79
|
+
assert sampled.shape == seq.shape
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Citations
|
|
84
|
+
|
|
85
|
+
```bibtex
|
|
86
|
+
@article{Li2024AutoregressiveIG,
|
|
87
|
+
title = {Autoregressive Image Generation without Vector Quantization},
|
|
88
|
+
author = {Tianhong Li and Yonglong Tian and He Li and Mingyang Deng and Kaiming He},
|
|
89
|
+
journal = {ArXiv},
|
|
90
|
+
year = {2024},
|
|
91
|
+
volume = {abs/2406.11838},
|
|
92
|
+
url = {https://api.semanticscholar.org/CorpusID:270560593}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
<img src="./ar-diffusion.png" width="400px"></img>
|
|
2
|
+
|
|
3
|
+
## Autoregressive Diffusion - Pytorch (wip)
|
|
4
|
+
|
|
5
|
+
Implementation of the architecture behind <a href="https://arxiv.org/abs/2406.11838">Autoregressive Image Generation without Vector Quantization</a> in Pytorch
|
|
6
|
+
|
|
7
|
+
You can discuss the paper temporarily [here](https://discord.com/invite/9myQVTbN)
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
$ pip install autoregressive-diffusion-pytorch
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import torch
|
|
19
|
+
from autoregressive_diffusion_pytorch import AutoregressiveDiffusion
|
|
20
|
+
|
|
21
|
+
model = AutoregressiveDiffusion(
|
|
22
|
+
dim = 512,
|
|
23
|
+
max_seq_len = 32
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
seq = torch.randn(3, 32, 512)
|
|
27
|
+
|
|
28
|
+
loss = model(seq)
|
|
29
|
+
loss.backward()
|
|
30
|
+
|
|
31
|
+
sampled = model.sample(batch_size = 3)
|
|
32
|
+
|
|
33
|
+
assert sampled.shape == seq.shape
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Citations
|
|
38
|
+
|
|
39
|
+
```bibtex
|
|
40
|
+
@article{Li2024AutoregressiveIG,
|
|
41
|
+
title = {Autoregressive Image Generation without Vector Quantization},
|
|
42
|
+
author = {Tianhong Li and Yonglong Tian and He Li and Mingyang Deng and Kaiming He},
|
|
43
|
+
journal = {ArXiv},
|
|
44
|
+
year = {2024},
|
|
45
|
+
volume = {abs/2406.11838},
|
|
46
|
+
url = {https://api.semanticscholar.org/CorpusID:270560593}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
Binary file
|
autoregressive_diffusion_pytorch-0.0.1/autoregressive_diffusion_pytorch/autoregressive_diffusion.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
from functools import partial
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn, pi
|
|
6
|
+
from torch.special import expm1
|
|
7
|
+
import torch.nn.functional as F
|
|
8
|
+
from torch.nn import Module, ModuleList
|
|
9
|
+
|
|
10
|
+
import einx
|
|
11
|
+
from einops import rearrange, repeat, reduce, pack, unpack
|
|
12
|
+
from einops.layers.torch import Rearrange
|
|
13
|
+
|
|
14
|
+
from tqdm import tqdm
|
|
15
|
+
|
|
16
|
+
from x_transformers import (
|
|
17
|
+
ContinuousTransformerWrapper,
|
|
18
|
+
Decoder
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# helpers
|
|
22
|
+
|
|
23
|
+
def exists(v):
|
|
24
|
+
return v is not None
|
|
25
|
+
|
|
26
|
+
def default(v, d):
|
|
27
|
+
return v if exists(v) else d
|
|
28
|
+
|
|
29
|
+
def divisible_by(num, den):
|
|
30
|
+
return (num % den) == 0
|
|
31
|
+
|
|
32
|
+
# tensor helpers
|
|
33
|
+
|
|
34
|
+
def log(t, eps = 1e-20):
|
|
35
|
+
return torch.log(t.clamp(min = eps))
|
|
36
|
+
|
|
37
|
+
def safe_div(num, den, eps = 1e-5):
|
|
38
|
+
return num / den.clamp(min = eps)
|
|
39
|
+
|
|
40
|
+
def right_pad_dims_to(x, t):
|
|
41
|
+
padding_dims = x.ndim - t.ndim
|
|
42
|
+
|
|
43
|
+
if padding_dims <= 0:
|
|
44
|
+
return t
|
|
45
|
+
|
|
46
|
+
return t.view(*t.shape, *((1,) * padding_dims))
|
|
47
|
+
|
|
48
|
+
def pack_one(t, pattern):
|
|
49
|
+
packed, ps = pack([t], pattern)
|
|
50
|
+
|
|
51
|
+
def unpack_one(to_unpack, unpack_pattern = None):
|
|
52
|
+
unpacked, = unpack(to_unpack, ps, default(unpack_pattern, pattern))
|
|
53
|
+
return unpacked
|
|
54
|
+
|
|
55
|
+
return packed, unpack_one
|
|
56
|
+
|
|
57
|
+
# sinusoidal embedding
|
|
58
|
+
|
|
59
|
+
class AdaptiveLayerNorm(Module):
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
dim,
|
|
63
|
+
dim_condition = None
|
|
64
|
+
):
|
|
65
|
+
super().__init__()
|
|
66
|
+
dim_condition = default(dim_condition, dim)
|
|
67
|
+
|
|
68
|
+
self.ln = nn.LayerNorm(dim, elementwise_affine = False)
|
|
69
|
+
self.to_gamma = nn.Linear(dim_condition, dim, bias = False)
|
|
70
|
+
nn.init.zeros_(self.to_gamma.weight)
|
|
71
|
+
|
|
72
|
+
def forward(self, x, *, condition):
|
|
73
|
+
normed = self.ln(x)
|
|
74
|
+
gamma = self.to_gamma(condition)
|
|
75
|
+
return normed * (gamma + 1.)
|
|
76
|
+
|
|
77
|
+
class LearnedSinusoidalPosEmb(Module):
|
|
78
|
+
def __init__(self, dim):
|
|
79
|
+
super().__init__()
|
|
80
|
+
assert divisible_by(dim, 2)
|
|
81
|
+
half_dim = dim // 2
|
|
82
|
+
self.weights = nn.Parameter(torch.randn(half_dim))
|
|
83
|
+
|
|
84
|
+
def forward(self, x):
|
|
85
|
+
x = rearrange(x, 'b -> b 1')
|
|
86
|
+
freqs = x * rearrange(self.weights, 'd -> 1 d') * 2 * pi
|
|
87
|
+
fouriered = torch.cat((freqs.sin(), freqs.cos()), dim = -1)
|
|
88
|
+
fouriered = torch.cat((x, fouriered), dim = -1)
|
|
89
|
+
return fouriered
|
|
90
|
+
|
|
91
|
+
# simple mlp
|
|
92
|
+
|
|
93
|
+
class MLP(Module):
|
|
94
|
+
def __init__(
|
|
95
|
+
self,
|
|
96
|
+
dim,
|
|
97
|
+
dim_cond,
|
|
98
|
+
depth = 3,
|
|
99
|
+
width = 1024,
|
|
100
|
+
dropout = 0.
|
|
101
|
+
):
|
|
102
|
+
super().__init__()
|
|
103
|
+
layers = ModuleList([])
|
|
104
|
+
|
|
105
|
+
self.to_time_emb = nn.Sequential(
|
|
106
|
+
LearnedSinusoidalPosEmb(dim_cond),
|
|
107
|
+
nn.Linear(dim_cond + 1, dim_cond),
|
|
108
|
+
nn.SiLU(),
|
|
109
|
+
nn.Dropout(dropout),
|
|
110
|
+
nn.Linear(dim_cond, dim_cond)
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
for _ in range(depth):
|
|
114
|
+
|
|
115
|
+
adaptive_layernorm = AdaptiveLayerNorm(
|
|
116
|
+
dim,
|
|
117
|
+
dim_condition = dim_cond
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
block = nn.Sequential(
|
|
121
|
+
nn.Linear(dim, dim),
|
|
122
|
+
nn.SiLU(),
|
|
123
|
+
nn.Linear(dim, dim)
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
layers.append(ModuleList([
|
|
127
|
+
adaptive_layernorm,
|
|
128
|
+
block
|
|
129
|
+
]))
|
|
130
|
+
|
|
131
|
+
self.layers = layers
|
|
132
|
+
|
|
133
|
+
def forward(
|
|
134
|
+
self,
|
|
135
|
+
noised,
|
|
136
|
+
*,
|
|
137
|
+
times,
|
|
138
|
+
cond
|
|
139
|
+
):
|
|
140
|
+
assert noised.ndim == 2
|
|
141
|
+
|
|
142
|
+
time_emb = self.to_time_emb(times)
|
|
143
|
+
cond = time_emb + cond
|
|
144
|
+
|
|
145
|
+
denoised = noised
|
|
146
|
+
|
|
147
|
+
for adaln, block in self.layers:
|
|
148
|
+
residual = denoised
|
|
149
|
+
denoised = adaln(denoised, condition = cond)
|
|
150
|
+
denoised = block(denoised) + residual
|
|
151
|
+
|
|
152
|
+
return denoised
|
|
153
|
+
|
|
154
|
+
# gaussian diffusion
|
|
155
|
+
|
|
156
|
+
def simple_linear_schedule(t, clip_min = 1e-9):
|
|
157
|
+
return (1. - t).clamp(min = clip_min)
|
|
158
|
+
|
|
159
|
+
def cosine_schedule(t, start = 0, end = 1, tau = 1, clip_min = 1e-9):
|
|
160
|
+
start, end, tau = map(torch.tensor, (start, end, tau))
|
|
161
|
+
power = 2 * tau
|
|
162
|
+
v_start = torch.cos(start * pi / 2) ** power
|
|
163
|
+
v_end = torch.cos(end * pi / 2) ** power
|
|
164
|
+
output = torch.cos((t * (end - start) + start) * pi / 2) ** power
|
|
165
|
+
output = (v_end - output) / (v_end - v_start)
|
|
166
|
+
return output.clamp(min = clip_min)
|
|
167
|
+
|
|
168
|
+
def gamma_to_alpha_sigma(gamma, scale = 1):
|
|
169
|
+
return torch.sqrt(gamma) * scale, torch.sqrt(1 - gamma)
|
|
170
|
+
|
|
171
|
+
def gamma_to_log_snr(gamma, scale = 1, eps = 1e-5):
|
|
172
|
+
return log(gamma * (scale ** 2) / (1. - gamma), eps = eps)
|
|
173
|
+
|
|
174
|
+
class GaussianDiffusion(Module):
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
model: MLP,
|
|
178
|
+
*,
|
|
179
|
+
timesteps = 1000,
|
|
180
|
+
sampling_timesteps = None,
|
|
181
|
+
use_ddim = True,
|
|
182
|
+
noise_schedule: Literal['linear', 'cosine'] = 'cosine',
|
|
183
|
+
objective: Literal['eps', 'v'] = 'v',
|
|
184
|
+
schedule_kwargs: dict = dict(),
|
|
185
|
+
min_snr_loss_weight = True,
|
|
186
|
+
min_snr_gamma = 5,
|
|
187
|
+
):
|
|
188
|
+
super().__init__()
|
|
189
|
+
self.model = model
|
|
190
|
+
self.objective = objective
|
|
191
|
+
|
|
192
|
+
if noise_schedule == 'linear':
|
|
193
|
+
self.gamma_schedule = simple_linear_schedule
|
|
194
|
+
elif noise_schedule == 'cosine':
|
|
195
|
+
self.gamma_schedule = cosine_schedule
|
|
196
|
+
else:
|
|
197
|
+
raise ValueError(f'invalid noise schedule {noise_schedule}')
|
|
198
|
+
|
|
199
|
+
# gamma schedules
|
|
200
|
+
|
|
201
|
+
self.gamma_schedule = partial(self.gamma_schedule, **schedule_kwargs)
|
|
202
|
+
|
|
203
|
+
self.timesteps = timesteps
|
|
204
|
+
self.sampling_timesteps = default(sampling_timesteps, timesteps)
|
|
205
|
+
|
|
206
|
+
self.use_ddim = use_ddim
|
|
207
|
+
|
|
208
|
+
# min snr loss weight
|
|
209
|
+
|
|
210
|
+
self.min_snr_loss_weight = min_snr_loss_weight
|
|
211
|
+
self.min_snr_gamma = min_snr_gamma
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def device(self):
|
|
215
|
+
return next(self.model.parameters()).device
|
|
216
|
+
|
|
217
|
+
def get_sampling_timesteps(self, batch, *, device):
|
|
218
|
+
times = torch.linspace(1., 0., self.sampling_timesteps + 1, device = device)
|
|
219
|
+
times = repeat(times, 't -> b t', b = batch)
|
|
220
|
+
times = torch.stack((times[:, :-1], times[:, 1:]), dim = 0)
|
|
221
|
+
times = times.unbind(dim = -1)
|
|
222
|
+
return times
|
|
223
|
+
|
|
224
|
+
@torch.no_grad()
|
|
225
|
+
def ddpm_sample(self, cond):
|
|
226
|
+
batch, device = cond.shape[0], self.device
|
|
227
|
+
|
|
228
|
+
time_pairs = self.get_sampling_timesteps(batch, device = device)
|
|
229
|
+
|
|
230
|
+
seq = torch.randn(cond.shape, device = device)
|
|
231
|
+
|
|
232
|
+
for time, time_next in tqdm(time_pairs, desc = 'sampling loop time step', total = self.timesteps, leave = False):
|
|
233
|
+
|
|
234
|
+
# get predicted x0
|
|
235
|
+
|
|
236
|
+
model_output = self.model(seq, times = time, cond = cond)
|
|
237
|
+
|
|
238
|
+
# get log(snr)
|
|
239
|
+
|
|
240
|
+
gamma = self.gamma_schedule(time)
|
|
241
|
+
gamma_next = self.gamma_schedule(time_next)
|
|
242
|
+
|
|
243
|
+
gamma, gamma_next = map(partial(right_pad_dims_to, seq), (gamma, gamma_next))
|
|
244
|
+
|
|
245
|
+
# get alpha sigma of time and next time
|
|
246
|
+
|
|
247
|
+
alpha, sigma = gamma_to_alpha_sigma(gamma)
|
|
248
|
+
alpha_next, sigma_next = gamma_to_alpha_sigma(gamma_next)
|
|
249
|
+
|
|
250
|
+
# calculate x0 and noise
|
|
251
|
+
|
|
252
|
+
if self.objective == 'eps':
|
|
253
|
+
x_start = safe_div(seq - sigma * model_output, alpha)
|
|
254
|
+
|
|
255
|
+
elif self.objective == 'v':
|
|
256
|
+
x_start = alpha * seq - sigma * model_output
|
|
257
|
+
|
|
258
|
+
# clip x0
|
|
259
|
+
|
|
260
|
+
x_start.clamp_(-1., 1.)
|
|
261
|
+
|
|
262
|
+
# derive posterior mean and variance
|
|
263
|
+
|
|
264
|
+
log_snr, log_snr_next = map(gamma_to_log_snr, (gamma, gamma_next))
|
|
265
|
+
|
|
266
|
+
c = -expm1(log_snr - log_snr_next)
|
|
267
|
+
|
|
268
|
+
mean = alpha_next * (seq * (1 - c) / alpha + c * x_start)
|
|
269
|
+
variance = (sigma_next ** 2) * c
|
|
270
|
+
log_variance = log(variance)
|
|
271
|
+
|
|
272
|
+
# get noise
|
|
273
|
+
|
|
274
|
+
noise = einx.where(
|
|
275
|
+
'b, b d, -> b d',
|
|
276
|
+
time_next > 0,
|
|
277
|
+
torch.randn_like(seq),
|
|
278
|
+
0.
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
seq = mean + (0.5 * log_variance).exp() * noise
|
|
282
|
+
|
|
283
|
+
print(seq.shape)
|
|
284
|
+
return seq
|
|
285
|
+
|
|
286
|
+
@torch.no_grad()
|
|
287
|
+
def ddim_sample(self, cond):
|
|
288
|
+
batch, device = cond.shape[0], self.device
|
|
289
|
+
|
|
290
|
+
time_pairs = self.get_sampling_timesteps(batch, device = device)
|
|
291
|
+
|
|
292
|
+
seq = torch.randn(cond.shape, device = device)
|
|
293
|
+
|
|
294
|
+
for times, times_next in tqdm(time_pairs, desc = 'sampling loop time step', leave = False):
|
|
295
|
+
|
|
296
|
+
# get times and noise levels
|
|
297
|
+
|
|
298
|
+
gamma = self.gamma_schedule(times)
|
|
299
|
+
gamma_next = self.gamma_schedule(times_next)
|
|
300
|
+
|
|
301
|
+
padded_gamma, padded_gamma_next = map(partial(right_pad_dims_to, seq), (gamma, gamma_next))
|
|
302
|
+
|
|
303
|
+
alpha, sigma = gamma_to_alpha_sigma(padded_gamma)
|
|
304
|
+
alpha_next, sigma_next = gamma_to_alpha_sigma(padded_gamma_next)
|
|
305
|
+
|
|
306
|
+
# predict x0
|
|
307
|
+
|
|
308
|
+
model_output = self.model(seq, times = times, cond = cond)
|
|
309
|
+
|
|
310
|
+
# calculate x0 and noise
|
|
311
|
+
|
|
312
|
+
if self.objective == 'eps':
|
|
313
|
+
x_start = safe_div(seq - sigma * model_output, alpha)
|
|
314
|
+
|
|
315
|
+
elif self.objective == 'v':
|
|
316
|
+
x_start = alpha * seq - sigma * model_output
|
|
317
|
+
|
|
318
|
+
# clip x0
|
|
319
|
+
|
|
320
|
+
x_start.clamp_(-1., 1.)
|
|
321
|
+
|
|
322
|
+
# get predicted noise
|
|
323
|
+
|
|
324
|
+
pred_noise = safe_div(seq - alpha * x_start, sigma)
|
|
325
|
+
|
|
326
|
+
# calculate x next
|
|
327
|
+
|
|
328
|
+
seq = x_start * alpha_next + pred_noise * sigma_next
|
|
329
|
+
|
|
330
|
+
return seq
|
|
331
|
+
|
|
332
|
+
@torch.no_grad()
|
|
333
|
+
def sample(self, *, cond, batch_size = 16):
|
|
334
|
+
sample_fn = self.ddpm_sample if not self.use_ddim else self.ddim_sample
|
|
335
|
+
return sample_fn(cond)
|
|
336
|
+
|
|
337
|
+
def forward(self, seq, *args, cond, **kwargs):
|
|
338
|
+
|
|
339
|
+
batch, device = seq.shape[0], seq.device
|
|
340
|
+
|
|
341
|
+
# sample random times
|
|
342
|
+
|
|
343
|
+
times = torch.rand((batch,), device = device)
|
|
344
|
+
|
|
345
|
+
# noise sample
|
|
346
|
+
|
|
347
|
+
noise = torch.randn_like(seq)
|
|
348
|
+
|
|
349
|
+
gamma = self.gamma_schedule(times)
|
|
350
|
+
padded_gamma = right_pad_dims_to(seq, gamma)
|
|
351
|
+
alpha, sigma = gamma_to_alpha_sigma(padded_gamma)
|
|
352
|
+
|
|
353
|
+
noised_seq = alpha * seq + sigma * noise
|
|
354
|
+
|
|
355
|
+
# predict and take gradient step
|
|
356
|
+
|
|
357
|
+
pred = self.model(noised_seq, times = times, cond = cond)
|
|
358
|
+
|
|
359
|
+
if self.objective == 'eps':
|
|
360
|
+
target = noise
|
|
361
|
+
|
|
362
|
+
elif self.objective == 'v':
|
|
363
|
+
target = alpha * noise - sigma * seq
|
|
364
|
+
|
|
365
|
+
loss = F.mse_loss(pred, target, reduction = 'none')
|
|
366
|
+
loss = reduce(loss, 'b ... -> b', 'mean')
|
|
367
|
+
|
|
368
|
+
# min snr loss weight
|
|
369
|
+
|
|
370
|
+
snr = (alpha * alpha) / (sigma * sigma)
|
|
371
|
+
maybe_clipped_snr = snr.clone()
|
|
372
|
+
|
|
373
|
+
if self.min_snr_loss_weight:
|
|
374
|
+
maybe_clipped_snr.clamp_(max = self.min_snr_gamma)
|
|
375
|
+
|
|
376
|
+
if self.objective == 'eps':
|
|
377
|
+
loss_weight = maybe_clipped_snr / snr
|
|
378
|
+
|
|
379
|
+
elif self.objective == 'v':
|
|
380
|
+
loss_weight = maybe_clipped_snr / (snr + 1)
|
|
381
|
+
|
|
382
|
+
return (loss * loss_weight).mean()
|
|
383
|
+
|
|
384
|
+
# main model, a decoder with continuous wrapper + small denoising mlp
|
|
385
|
+
|
|
386
|
+
class AutoregressiveDiffusion(Module):
|
|
387
|
+
def __init__(
|
|
388
|
+
self,
|
|
389
|
+
dim,
|
|
390
|
+
*,
|
|
391
|
+
max_seq_len,
|
|
392
|
+
depth = 8,
|
|
393
|
+
dim_head = 64,
|
|
394
|
+
heads = 8,
|
|
395
|
+
mlp_depth = 3,
|
|
396
|
+
mlp_width = 1024,
|
|
397
|
+
decoder_kwargs: dict = dict(),
|
|
398
|
+
mlp_kwargs: dict = dict(),
|
|
399
|
+
diffusion_kwargs: dict = dict(
|
|
400
|
+
timesteps = 1000,
|
|
401
|
+
sampling_timesteps = 100,
|
|
402
|
+
use_ddim = False
|
|
403
|
+
)
|
|
404
|
+
):
|
|
405
|
+
super().__init__()
|
|
406
|
+
|
|
407
|
+
self.start_token = nn.Parameter(torch.zeros(dim))
|
|
408
|
+
self.max_seq_len = max_seq_len
|
|
409
|
+
self.abs_pos_emb = nn.Embedding(max_seq_len, dim)
|
|
410
|
+
|
|
411
|
+
self.transformer = Decoder(
|
|
412
|
+
dim = dim,
|
|
413
|
+
depth = depth,
|
|
414
|
+
heads = heads,
|
|
415
|
+
attn_dim_head = dim_head,
|
|
416
|
+
**decoder_kwargs
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
self.denoiser = MLP(
|
|
420
|
+
dim = dim,
|
|
421
|
+
dim_cond = dim,
|
|
422
|
+
depth = mlp_depth,
|
|
423
|
+
width = mlp_width,
|
|
424
|
+
**mlp_kwargs
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
self.diffusion = GaussianDiffusion(
|
|
428
|
+
self.denoiser,
|
|
429
|
+
**diffusion_kwargs
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
def sample(
|
|
433
|
+
self,
|
|
434
|
+
batch_size = 1
|
|
435
|
+
):
|
|
436
|
+
out = repeat(self.start_token, 'd -> b 1 d', b = batch_size)
|
|
437
|
+
|
|
438
|
+
for _ in tqdm(range(self.max_seq_len), desc = 'tokens'):
|
|
439
|
+
|
|
440
|
+
cond = self.transformer(out)
|
|
441
|
+
last_cond = cond[:, -1]
|
|
442
|
+
|
|
443
|
+
denoised_pred = self.diffusion.sample(cond = last_cond)
|
|
444
|
+
|
|
445
|
+
denoised_pred = rearrange(denoised_pred, 'b d -> b 1 d')
|
|
446
|
+
out = torch.cat((out, denoised_pred), dim = 1)
|
|
447
|
+
|
|
448
|
+
return out[:, 1:]
|
|
449
|
+
|
|
450
|
+
def forward(
|
|
451
|
+
self,
|
|
452
|
+
seq
|
|
453
|
+
):
|
|
454
|
+
b = seq.shape[0]
|
|
455
|
+
|
|
456
|
+
# append start tokens
|
|
457
|
+
|
|
458
|
+
start_token = repeat(self.start_token, 'd -> b 1 d', b = b)
|
|
459
|
+
seq = torch.cat((start_token, seq), dim = 1)
|
|
460
|
+
|
|
461
|
+
# break into seq and the continuous targets to be predicted
|
|
462
|
+
|
|
463
|
+
seq, target = seq[:, :-1], seq[:, 1:]
|
|
464
|
+
|
|
465
|
+
cond = self.transformer(seq)
|
|
466
|
+
|
|
467
|
+
# pack batch and sequence dimensions, so to train each token with different noise levels
|
|
468
|
+
|
|
469
|
+
target, _ = pack_one(target, '* d')
|
|
470
|
+
cond, _ = pack_one(cond, '* d')
|
|
471
|
+
|
|
472
|
+
diffusion_loss = self.diffusion(target, cond = cond)
|
|
473
|
+
|
|
474
|
+
return diffusion_loss
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "autoregressive-diffusion-pytorch"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "Autoregressive Diffusion - Pytorch"
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Phil Wang", email = "lucidrains@gmail.com" }
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">= 3.8"
|
|
10
|
+
license = { file = "LICENSE" }
|
|
11
|
+
keywords = [
|
|
12
|
+
'artificial intelligence',
|
|
13
|
+
'deep learning',
|
|
14
|
+
'transformers',
|
|
15
|
+
'denoising diffusion',
|
|
16
|
+
]
|
|
17
|
+
classifiers=[
|
|
18
|
+
'Development Status :: 4 - Beta',
|
|
19
|
+
'Intended Audience :: Developers',
|
|
20
|
+
'Topic :: Scientific/Engineering :: Artificial Intelligence',
|
|
21
|
+
'License :: OSI Approved :: MIT License',
|
|
22
|
+
'Programming Language :: Python :: 3.8',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
dependencies = [
|
|
26
|
+
'einx>=0.3.0',
|
|
27
|
+
'einops>=0.8.0',
|
|
28
|
+
'x-transformers>=1.31.14',
|
|
29
|
+
'torch>=2.0',
|
|
30
|
+
'tqdm'
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://pypi.org/project/autoregressive-diffusion-pytorch/"
|
|
35
|
+
Repository = "https://github.com/lucidrains/autoregressive-diffusion-pytorch"
|
|
36
|
+
|
|
37
|
+
[project.optional-dependencies]
|
|
38
|
+
examples = ["tqdm", "numpy"]
|
|
39
|
+
|
|
40
|
+
[build-system]
|
|
41
|
+
requires = ["hatchling"]
|
|
42
|
+
build-backend = "hatchling.build"
|
|
43
|
+
|
|
44
|
+
[tool.hatch.metadata]
|
|
45
|
+
allow-direct-references = true
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build.targets.wheel]
|
|
48
|
+
packages = ["autoregressive-diffusion-pytorch"]
|