discrete-distribution-network 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.
- discrete_distribution_network-0.0.1/.github/workflows/python-publish.yml +36 -0
- discrete_distribution_network-0.0.1/.github/workflows/test.yml +21 -0
- discrete_distribution_network-0.0.1/.gitignore +207 -0
- discrete_distribution_network-0.0.1/LICENSE +21 -0
- discrete_distribution_network-0.0.1/PKG-INFO +65 -0
- discrete_distribution_network-0.0.1/README.md +21 -0
- discrete_distribution_network-0.0.1/ddn.png +0 -0
- discrete_distribution_network-0.0.1/discrete_distribution_network/__init__.py +5 -0
- discrete_distribution_network-0.0.1/discrete_distribution_network/ddn.py +162 -0
- discrete_distribution_network-0.0.1/pyproject.toml +58 -0
- discrete_distribution_network-0.0.1/tests/test_ddn.py +29 -0
- discrete_distribution_network-0.0.1/train_ddn.py +59 -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,21 @@
|
|
|
1
|
+
name: Pytest
|
|
2
|
+
on: [push, pull_request]
|
|
3
|
+
|
|
4
|
+
jobs:
|
|
5
|
+
build:
|
|
6
|
+
|
|
7
|
+
runs-on: ubuntu-latest
|
|
8
|
+
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v4
|
|
11
|
+
- name: Set up Python 3.10
|
|
12
|
+
uses: actions/setup-python@v5
|
|
13
|
+
with:
|
|
14
|
+
python-version: "3.10"
|
|
15
|
+
- name: Install dependencies
|
|
16
|
+
run: |
|
|
17
|
+
python -m pip install --upgrade pip
|
|
18
|
+
python -m pip install -e .[test]
|
|
19
|
+
- name: Test with pytest
|
|
20
|
+
run: |
|
|
21
|
+
python -m pytest tests/
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
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
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
#poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
#pdm.lock
|
|
116
|
+
#pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
#pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# SageMath parsed files
|
|
135
|
+
*.sage.py
|
|
136
|
+
|
|
137
|
+
# Environments
|
|
138
|
+
.env
|
|
139
|
+
.envrc
|
|
140
|
+
.venv
|
|
141
|
+
env/
|
|
142
|
+
venv/
|
|
143
|
+
ENV/
|
|
144
|
+
env.bak/
|
|
145
|
+
venv.bak/
|
|
146
|
+
|
|
147
|
+
# Spyder project settings
|
|
148
|
+
.spyderproject
|
|
149
|
+
.spyproject
|
|
150
|
+
|
|
151
|
+
# Rope project settings
|
|
152
|
+
.ropeproject
|
|
153
|
+
|
|
154
|
+
# mkdocs documentation
|
|
155
|
+
/site
|
|
156
|
+
|
|
157
|
+
# mypy
|
|
158
|
+
.mypy_cache/
|
|
159
|
+
.dmypy.json
|
|
160
|
+
dmypy.json
|
|
161
|
+
|
|
162
|
+
# Pyre type checker
|
|
163
|
+
.pyre/
|
|
164
|
+
|
|
165
|
+
# pytype static type analyzer
|
|
166
|
+
.pytype/
|
|
167
|
+
|
|
168
|
+
# Cython debug symbols
|
|
169
|
+
cython_debug/
|
|
170
|
+
|
|
171
|
+
# PyCharm
|
|
172
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
173
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
174
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
175
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
176
|
+
#.idea/
|
|
177
|
+
|
|
178
|
+
# Abstra
|
|
179
|
+
# Abstra is an AI-powered process automation framework.
|
|
180
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
181
|
+
# Learn more at https://abstra.io/docs
|
|
182
|
+
.abstra/
|
|
183
|
+
|
|
184
|
+
# Visual Studio Code
|
|
185
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
186
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
188
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
189
|
+
# .vscode/
|
|
190
|
+
|
|
191
|
+
# Ruff stuff:
|
|
192
|
+
.ruff_cache/
|
|
193
|
+
|
|
194
|
+
# PyPI configuration file
|
|
195
|
+
.pypirc
|
|
196
|
+
|
|
197
|
+
# Cursor
|
|
198
|
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
|
199
|
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
|
200
|
+
# refer to https://docs.cursor.com/context/ignore-files
|
|
201
|
+
.cursorignore
|
|
202
|
+
.cursorindexingignore
|
|
203
|
+
|
|
204
|
+
# Marimo
|
|
205
|
+
marimo/_static/
|
|
206
|
+
marimo/_lsp/
|
|
207
|
+
__marimo__/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 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,65 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: discrete-distribution-network
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Discrete Distribution Network
|
|
5
|
+
Project-URL: Homepage, https://pypi.org/project/discrete-distribution-network/
|
|
6
|
+
Project-URL: Repository, https://github.com/lucidrains/discrete-distribution-network
|
|
7
|
+
Author-email: Phil Wang <lucidrains@gmail.com>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2025 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,generative modeling
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
35
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
36
|
+
Requires-Python: >=3.9
|
|
37
|
+
Requires-Dist: einops>=0.8.1
|
|
38
|
+
Requires-Dist: torch>=2.4
|
|
39
|
+
Requires-Dist: x-mlps-pytorch>=0.0.30
|
|
40
|
+
Provides-Extra: examples
|
|
41
|
+
Provides-Extra: test
|
|
42
|
+
Requires-Dist: pytest; extra == 'test'
|
|
43
|
+
Description-Content-Type: text/markdown
|
|
44
|
+
|
|
45
|
+
<img src="./ddn.png" width="400px"></img>
|
|
46
|
+
|
|
47
|
+
## Discrete Distribution Network (wip)
|
|
48
|
+
|
|
49
|
+
Exploration into [Discrete Distribution Network](https://discrete-distribution-networks.github.io/), by Lei Yang out of Beijing
|
|
50
|
+
|
|
51
|
+
Besides the split-and-prune, may also throw in an option for crossover (mixing of top 2 nodes to replace the pruned)
|
|
52
|
+
|
|
53
|
+
## Citations
|
|
54
|
+
|
|
55
|
+
```bibtex
|
|
56
|
+
@misc{yang2025discretedistributionnetworks,
|
|
57
|
+
title = {Discrete Distribution Networks},
|
|
58
|
+
author = {Lei Yang},
|
|
59
|
+
year = {2025},
|
|
60
|
+
eprint = {2401.00036},
|
|
61
|
+
archivePrefix = {arXiv},
|
|
62
|
+
primaryClass = {cs.CV},
|
|
63
|
+
url = {https://arxiv.org/abs/2401.00036},
|
|
64
|
+
}
|
|
65
|
+
```
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
<img src="./ddn.png" width="400px"></img>
|
|
2
|
+
|
|
3
|
+
## Discrete Distribution Network (wip)
|
|
4
|
+
|
|
5
|
+
Exploration into [Discrete Distribution Network](https://discrete-distribution-networks.github.io/), by Lei Yang out of Beijing
|
|
6
|
+
|
|
7
|
+
Besides the split-and-prune, may also throw in an option for crossover (mixing of top 2 nodes to replace the pruned)
|
|
8
|
+
|
|
9
|
+
## Citations
|
|
10
|
+
|
|
11
|
+
```bibtex
|
|
12
|
+
@misc{yang2025discretedistributionnetworks,
|
|
13
|
+
title = {Discrete Distribution Networks},
|
|
14
|
+
author = {Lei Yang},
|
|
15
|
+
year = {2025},
|
|
16
|
+
eprint = {2401.00036},
|
|
17
|
+
archivePrefix = {arXiv},
|
|
18
|
+
primaryClass = {cs.CV},
|
|
19
|
+
url = {https://arxiv.org/abs/2401.00036},
|
|
20
|
+
}
|
|
21
|
+
```
|
|
Binary file
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Callable
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn, arange, tensor
|
|
6
|
+
import torch.nn.functional as F
|
|
7
|
+
from torch.nn import Module
|
|
8
|
+
|
|
9
|
+
from einops import rearrange, einsum
|
|
10
|
+
|
|
11
|
+
from x_mlps_pytorch.ensemble import Ensemble
|
|
12
|
+
|
|
13
|
+
# helpers
|
|
14
|
+
|
|
15
|
+
def exists(v):
|
|
16
|
+
return v is not None
|
|
17
|
+
|
|
18
|
+
def default(v, d):
|
|
19
|
+
return v if exists(v) else d
|
|
20
|
+
|
|
21
|
+
# classes
|
|
22
|
+
|
|
23
|
+
class GuidedSampler(Module):
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
dim, # input feature dimension
|
|
27
|
+
dim_query = 3, # channels of image (default 3 for rgb)
|
|
28
|
+
codebook_size = 10, # K in paper
|
|
29
|
+
network: Module | None = None,
|
|
30
|
+
distance_fn: Callable | None = None,
|
|
31
|
+
split_thres = 2.,
|
|
32
|
+
prune_thres = 0.5,
|
|
33
|
+
min_total_count_before_split_prune = 100
|
|
34
|
+
):
|
|
35
|
+
super().__init__()
|
|
36
|
+
|
|
37
|
+
if not exists(network):
|
|
38
|
+
network = nn.Conv2d(dim, dim_query, 1, bias = False)
|
|
39
|
+
|
|
40
|
+
self.to_key_values = Ensemble(network, ensemble_size = codebook_size)
|
|
41
|
+
self.distance_fn = default(distance_fn, torch.cdist)
|
|
42
|
+
|
|
43
|
+
# split and prune related
|
|
44
|
+
|
|
45
|
+
self.register_buffer('counts', torch.zeros(codebook_size).long())
|
|
46
|
+
|
|
47
|
+
self.split_thres = split_thres / codebook_size
|
|
48
|
+
self.prune_thres = prune_thres / codebook_size
|
|
49
|
+
self.min_total_count_before_split_prune = min_total_count_before_split_prune
|
|
50
|
+
|
|
51
|
+
@torch.no_grad()
|
|
52
|
+
def split_and_prune_(
|
|
53
|
+
self
|
|
54
|
+
):
|
|
55
|
+
# following Algorithm 1 in the paper
|
|
56
|
+
|
|
57
|
+
counts = self.counts
|
|
58
|
+
total_count = counts.sum()
|
|
59
|
+
|
|
60
|
+
if total_count < self.min_total_count_before_split_prune:
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
count_max, count_max_index = counts.max(dim = -1)
|
|
64
|
+
count_min, count_min_index = counts.min(dim = -1)
|
|
65
|
+
|
|
66
|
+
if (
|
|
67
|
+
((count_max / total_count) <= self.split_thres) &
|
|
68
|
+
((count_min / total_count) >= self.prune_thres)
|
|
69
|
+
).all():
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
codebook_params = self.to_key_values.param_values
|
|
73
|
+
half_count_max = count_max // 2
|
|
74
|
+
|
|
75
|
+
# update the counts
|
|
76
|
+
|
|
77
|
+
self.counts[count_max_index] = half_count_max
|
|
78
|
+
self.counts[count_min_index] = half_count_max + 1 # adds 1 to k_new for some reason
|
|
79
|
+
|
|
80
|
+
# update the params
|
|
81
|
+
|
|
82
|
+
for codebook_param in codebook_params:
|
|
83
|
+
split = codebook_param[count_max]
|
|
84
|
+
|
|
85
|
+
# prune by replacement
|
|
86
|
+
codebook_param[count_min].copy_(split)
|
|
87
|
+
|
|
88
|
+
# take care of grad if present
|
|
89
|
+
if exists(codebook_param.grad):
|
|
90
|
+
codebook_param.grad[count_min].zero_()
|
|
91
|
+
|
|
92
|
+
def forward_for_codes(
|
|
93
|
+
self,
|
|
94
|
+
features, # (b d h w)
|
|
95
|
+
codes # (b) | ()
|
|
96
|
+
):
|
|
97
|
+
if codes.numel() == 1:
|
|
98
|
+
return self.to_key_values.forward_one(features, id = codes.item())
|
|
99
|
+
|
|
100
|
+
return self.to_key_values(features, ids = codes, each_batch_sample = True)
|
|
101
|
+
|
|
102
|
+
def forward(
|
|
103
|
+
self,
|
|
104
|
+
features, # (b d h w)
|
|
105
|
+
query, # (b c h w)
|
|
106
|
+
):
|
|
107
|
+
batch, device = query.shape[0], query.device
|
|
108
|
+
|
|
109
|
+
key_values = self.to_key_values(features)
|
|
110
|
+
|
|
111
|
+
# get the l2 distance
|
|
112
|
+
|
|
113
|
+
distance = self.distance_fn(
|
|
114
|
+
rearrange(query, 'b c h w -> b 1 (c h w)'),
|
|
115
|
+
rearrange(key_values, 'k b c h w -> b k (c h w)')
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
distance = rearrange(distance, 'b 1 k -> b k')
|
|
119
|
+
|
|
120
|
+
# select the code parameters that produced the image that is closest to the query
|
|
121
|
+
|
|
122
|
+
codes = distance.argmin(dim = -1)
|
|
123
|
+
|
|
124
|
+
if self.training:
|
|
125
|
+
self.counts.scatter_add_(0, codes, torch.ones_like(codes))
|
|
126
|
+
|
|
127
|
+
# some tensor gymnastics to select out the image across batch
|
|
128
|
+
|
|
129
|
+
key_values = rearrange(key_values, 'k b ... -> b k ...')
|
|
130
|
+
|
|
131
|
+
codes_for_indexing = rearrange(codes, 'b -> b 1')
|
|
132
|
+
batch_for_indexing = arange(batch, device = device)[:, None]
|
|
133
|
+
|
|
134
|
+
sel_key_values = key_values[batch_for_indexing, codes_for_indexing]
|
|
135
|
+
sel_key_values = rearrange(sel_key_values, 'b 1 ... -> b ...')
|
|
136
|
+
|
|
137
|
+
# commit loss
|
|
138
|
+
|
|
139
|
+
commit_loss = F.mse_loss(sel_key_values, query)
|
|
140
|
+
|
|
141
|
+
return sel_key_values, codes, commit_loss
|
|
142
|
+
|
|
143
|
+
class Network(Module):
|
|
144
|
+
def __init__(
|
|
145
|
+
self,
|
|
146
|
+
dim
|
|
147
|
+
):
|
|
148
|
+
super().__init__()
|
|
149
|
+
|
|
150
|
+
class DDN(Module):
|
|
151
|
+
def __init__(
|
|
152
|
+
self
|
|
153
|
+
):
|
|
154
|
+
super().__init__()
|
|
155
|
+
|
|
156
|
+
# trainer
|
|
157
|
+
|
|
158
|
+
class Trainer(Module):
|
|
159
|
+
def __init__(
|
|
160
|
+
self,
|
|
161
|
+
):
|
|
162
|
+
super().__init__()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "discrete-distribution-network"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "Discrete Distribution Network"
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Phil Wang", email = "lucidrains@gmail.com" }
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">= 3.9"
|
|
10
|
+
license = { file = "LICENSE" }
|
|
11
|
+
keywords = [
|
|
12
|
+
'artificial intelligence',
|
|
13
|
+
'deep learning',
|
|
14
|
+
'generative modeling',
|
|
15
|
+
]
|
|
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.9',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
dependencies = [
|
|
26
|
+
"einops>=0.8.1",
|
|
27
|
+
"torch>=2.4",
|
|
28
|
+
"x-mlps-pytorch>=0.0.30"
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://pypi.org/project/discrete-distribution-network/"
|
|
33
|
+
Repository = "https://github.com/lucidrains/discrete-distribution-network"
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
examples = []
|
|
37
|
+
test = [
|
|
38
|
+
"pytest"
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
pythonpath = [
|
|
43
|
+
"."
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[build-system]
|
|
47
|
+
requires = ["hatchling"]
|
|
48
|
+
build-backend = "hatchling.build"
|
|
49
|
+
|
|
50
|
+
[tool.rye]
|
|
51
|
+
managed = true
|
|
52
|
+
dev-dependencies = []
|
|
53
|
+
|
|
54
|
+
[tool.hatch.metadata]
|
|
55
|
+
allow-direct-references = true
|
|
56
|
+
|
|
57
|
+
[tool.hatch.build.targets.wheel]
|
|
58
|
+
packages = ["discrete_distribution_network"]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import tensor
|
|
5
|
+
|
|
6
|
+
def test_ddn():
|
|
7
|
+
from discrete_distribution_network.ddn import GuidedSampler
|
|
8
|
+
|
|
9
|
+
sampler = GuidedSampler(
|
|
10
|
+
dim = 16,
|
|
11
|
+
dim_query = 3,
|
|
12
|
+
codebook_size = 10
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
features = torch.randn(2, 16, 32, 32)
|
|
16
|
+
query_image = torch.randn(2, 3, 32, 32)
|
|
17
|
+
|
|
18
|
+
out, codes, commit_loss = sampler(features, query_image)
|
|
19
|
+
|
|
20
|
+
assert out.shape == query_image.shape
|
|
21
|
+
assert codes.shape == (2,)
|
|
22
|
+
assert commit_loss.numel() == 1
|
|
23
|
+
|
|
24
|
+
sampler.split_and_prune_()
|
|
25
|
+
|
|
26
|
+
# after much training
|
|
27
|
+
|
|
28
|
+
assert sampler.forward_for_codes(features, tensor([3, 5])).shape == (2, 3, 32, 32)
|
|
29
|
+
assert sampler.forward_for_codes(features, tensor(7)).shape == (2, 3, 32, 32)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# dependencies = [
|
|
3
|
+
# "discrete-distribution-network",
|
|
4
|
+
# "datasets",
|
|
5
|
+
# "wandb"
|
|
6
|
+
# ]
|
|
7
|
+
# ///
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
# hf datasets for easy oxford flowers training
|
|
12
|
+
|
|
13
|
+
import torchvision.transforms as T
|
|
14
|
+
from torch.utils.data import Dataset
|
|
15
|
+
from datasets import load_dataset
|
|
16
|
+
|
|
17
|
+
class OxfordFlowersDataset(Dataset):
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
image_size
|
|
21
|
+
):
|
|
22
|
+
self.ds = load_dataset('nelorth/oxford-flowers')['train']
|
|
23
|
+
|
|
24
|
+
self.transform = T.Compose([
|
|
25
|
+
T.Resize((image_size, image_size)),
|
|
26
|
+
T.PILToTensor()
|
|
27
|
+
])
|
|
28
|
+
|
|
29
|
+
def __len__(self):
|
|
30
|
+
return len(self.ds)
|
|
31
|
+
|
|
32
|
+
def __getitem__(self, idx):
|
|
33
|
+
pil = self.ds[idx]['image']
|
|
34
|
+
tensor = self.transform(pil)
|
|
35
|
+
return tensor / 255.
|
|
36
|
+
|
|
37
|
+
flowers_dataset = OxfordFlowersDataset(
|
|
38
|
+
image_size = 64
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# models and trainer
|
|
42
|
+
|
|
43
|
+
from discrete_distribution_network import DDN, Network, Trainer
|
|
44
|
+
|
|
45
|
+
model = Network(
|
|
46
|
+
dim = 64
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
ddn = DDN(model)
|
|
50
|
+
|
|
51
|
+
trainer = Trainer(
|
|
52
|
+
ddn,
|
|
53
|
+
dataset = flowers_dataset,
|
|
54
|
+
num_train_steps = 70_000,
|
|
55
|
+
sample_temperature = 1.5,
|
|
56
|
+
results_folder = './results' # samples will be saved periodically to this folder
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
trainer()
|