hyper-connections 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.
@@ -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,171 @@
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
+ # 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
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
@@ -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,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: hyper-connections
3
+ Version: 0.0.1
4
+ Summary: Hyper-Connections
5
+ Project-URL: Homepage, https://pypi.org/project/hyper-connections/
6
+ Project-URL: Repository, https://github.com/lucidrains/hyper-connections
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,residual
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.0
38
+ Requires-Dist: torch>=2.3
39
+ Provides-Extra: examples
40
+ Provides-Extra: test
41
+ Requires-Dist: pytest; extra == 'test'
42
+ Description-Content-Type: text/markdown
43
+
44
+ <img src="./hyper-connections.png" width="450px"></img>
45
+
46
+ ## Hyper Connections
47
+
48
+ Attempt to make the multiple residual stream approach proposed by Hyper-Connections paper by Bytedance AI more accessible as a reusable library, and for following any new research in this direction.
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ $ pip install hyper-connections
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ```python
59
+ import torch
60
+ from torch import nn
61
+
62
+ # a single branch layer
63
+
64
+ branch = nn.Linear(512, 512)
65
+
66
+ # before
67
+
68
+ residual = torch.randn(2, 1024, 512)
69
+
70
+ residual = branch(residual) + residual
71
+
72
+ # after, say 4 streams in paper
73
+
74
+ from hyper_connections import HyperConnections
75
+
76
+ expand_stream, reduce_stream = HyperConnections.get_expand_reduce_stream_functions(4)
77
+
78
+ # 1. wrap your branch function
79
+
80
+ hyper_conn_branch = HyperConnections(4, dim = 512, branch = branch)
81
+
82
+ # 2. expand to 4 streams, this must be done before your trunk, typically a for-loop with many branch functions
83
+
84
+ residual = expand_stream(residual)
85
+
86
+ # 3. forward your residual as usual into the wrapped branch function(s)
87
+
88
+ residual = hyper_conn_branch(residual)
89
+
90
+ # 4. reduce 4 streams with a summation, this has to be done after your for-loop trunk. for transformer, unsure whether to do before or after final norm
91
+
92
+ residual = reduce_stream(residual)
93
+ ```
94
+
95
+ ## Citation
96
+
97
+ ```bibtex
98
+ @article{Zhu2024HyperConnections,
99
+ title = {Hyper-Connections},
100
+ author = {Defa Zhu and Hongzhi Huang and Zihao Huang and Yutao Zeng and Yunyao Mao and Banggu Wu and Qiyang Min and Xun Zhou},
101
+ journal = {ArXiv},
102
+ year = {2024},
103
+ volume = {abs/2409.19606},
104
+ url = {https://api.semanticscholar.org/CorpusID:272987528}
105
+ }
106
+ ```
@@ -0,0 +1,63 @@
1
+ <img src="./hyper-connections.png" width="450px"></img>
2
+
3
+ ## Hyper Connections
4
+
5
+ Attempt to make the multiple residual stream approach proposed by Hyper-Connections paper by Bytedance AI more accessible as a reusable library, and for following any new research in this direction.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ $ pip install hyper-connections
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ import torch
17
+ from torch import nn
18
+
19
+ # a single branch layer
20
+
21
+ branch = nn.Linear(512, 512)
22
+
23
+ # before
24
+
25
+ residual = torch.randn(2, 1024, 512)
26
+
27
+ residual = branch(residual) + residual
28
+
29
+ # after, say 4 streams in paper
30
+
31
+ from hyper_connections import HyperConnections
32
+
33
+ expand_stream, reduce_stream = HyperConnections.get_expand_reduce_stream_functions(4)
34
+
35
+ # 1. wrap your branch function
36
+
37
+ hyper_conn_branch = HyperConnections(4, dim = 512, branch = branch)
38
+
39
+ # 2. expand to 4 streams, this must be done before your trunk, typically a for-loop with many branch functions
40
+
41
+ residual = expand_stream(residual)
42
+
43
+ # 3. forward your residual as usual into the wrapped branch function(s)
44
+
45
+ residual = hyper_conn_branch(residual)
46
+
47
+ # 4. reduce 4 streams with a summation, this has to be done after your for-loop trunk. for transformer, unsure whether to do before or after final norm
48
+
49
+ residual = reduce_stream(residual)
50
+ ```
51
+
52
+ ## Citation
53
+
54
+ ```bibtex
55
+ @article{Zhu2024HyperConnections,
56
+ title = {Hyper-Connections},
57
+ author = {Defa Zhu and Hongzhi Huang and Zihao Huang and Yutao Zeng and Yunyao Mao and Banggu Wu and Qiyang Min and Xun Zhou},
58
+ journal = {ArXiv},
59
+ year = {2024},
60
+ volume = {abs/2409.19606},
61
+ url = {https://api.semanticscholar.org/CorpusID:272987528}
62
+ }
63
+ ```
@@ -0,0 +1,3 @@
1
+ from hyper_connections.hyper_connections import (
2
+ HyperConnections
3
+ )
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+ from functools import partial
3
+ from random import randrange
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import Module
8
+ import torch.nn.functional as F
9
+
10
+ from einops import rearrange, repeat, reduce, einsum
11
+
12
+ # helper functions
13
+
14
+ def exists(v):
15
+ return v is not None
16
+
17
+ def default(v, d):
18
+ return v if exists(v) else d
19
+
20
+ # main class
21
+
22
+ # hyper connection residual streams
23
+
24
+ class HyperConnections(Module):
25
+ def __init__(
26
+ self,
27
+ num_residual_streams,
28
+ *,
29
+ dim,
30
+ branch: Module | None = None,
31
+ layer_index = None,
32
+ tanh = True,
33
+ ):
34
+ """
35
+ Appendix J, Algorithm2 in - https://arxiv.org/abs/2409.19606
36
+ """
37
+ super().__init__()
38
+
39
+ self.branch = branch
40
+
41
+ self.act = nn.Tanh() if tanh else nn.Identity()
42
+ self.norm = nn.RMSNorm(dim)
43
+
44
+ self.num_residual_streams = num_residual_streams
45
+ init_residual_index = default(layer_index, randrange(num_residual_streams)) % num_residual_streams # just choose one random residual stream if layer index not given
46
+
47
+ self.static_beta = nn.Parameter(torch.ones(num_residual_streams))
48
+
49
+ init_alpha0 = torch.zeros((num_residual_streams, 1))
50
+ init_alpha0[init_residual_index, 0] = 1.
51
+
52
+ self.static_alpha = nn.Parameter(torch.cat([init_alpha0, torch.eye(num_residual_streams)], dim = 1))
53
+
54
+ self.dynamic_alpha_fn = nn.Parameter(torch.zeros(dim, num_residual_streams + 1))
55
+ self.dynamic_alpha_scale = nn.Parameter(torch.ones(()) * 1e-2)
56
+ self.dynamic_beta_fn = nn.Parameter(torch.zeros(dim))
57
+ self.dynamic_beta_scale = nn.Parameter(torch.ones(()) * 1e-2)
58
+
59
+ @classmethod
60
+ def get_expand_reduce_stream_functions(cls, num_streams):
61
+ expand_fn = partial(repeat, pattern = 'b ... -> (b s) ...', s = num_streams)
62
+ reduce_fn = partial(reduce, pattern = '(b s) ... -> b ...', reduction = 'sum', s = num_streams)
63
+
64
+ return expand_fn, reduce_fn
65
+
66
+ def width_connection(self, residuals):
67
+ # width connection
68
+
69
+ residuals = rearrange(residuals, '(b s) ... d -> b ... s d', s = self.num_residual_streams)
70
+
71
+ normed = self.norm(residuals)
72
+
73
+ wc_weight = self.act(normed @ self.dynamic_alpha_fn)
74
+ dynamic_alpha = wc_weight * self.dynamic_alpha_scale
75
+ alpha = dynamic_alpha + self.static_alpha
76
+
77
+ dc_weight = self.act(normed @ self.dynamic_beta_fn)
78
+ dynamic_beta = dc_weight * self.dynamic_beta_scale
79
+ beta = dynamic_beta + self.static_beta
80
+
81
+ # width connection
82
+
83
+ mix_h = einsum(alpha, residuals, '... s t, ... s d -> ... t d')
84
+
85
+ branch_input, residuals = mix_h[..., 0, :], mix_h[..., 1:, :]
86
+
87
+ return branch_input, residuals, beta
88
+
89
+ def depth_connection(self, branch_output, residuals, beta):
90
+ # 'depth' connection
91
+
92
+ residuals = einsum(branch_output, beta, 'b ... d, b ... s -> b ... s d') + residuals
93
+ return rearrange(residuals, 'b ... s d -> (b s) ... d')
94
+
95
+ def forward(self, residuals, **branch_kwargs):
96
+
97
+ branch_input, residuals, beta = self.width_connection(residuals)
98
+
99
+ def add_residual_fn(branch_out):
100
+ return self.depth_connection(branch_out, residuals, beta)
101
+
102
+ if not exists(self.branch):
103
+ return branch_input, add_residual_fn
104
+
105
+ branch_output = self.branch(branch_input, **branch_kwargs)
106
+
107
+ return add_residual_fn(branch_output)
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "hyper-connections"
3
+ version = "0.0.1"
4
+ description = "Hyper-Connections"
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
+ 'residual',
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.0",
27
+ "torch>=2.3",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://pypi.org/project/hyper-connections/"
32
+ Repository = "https://github.com/lucidrains/hyper-connections"
33
+
34
+ [project.optional-dependencies]
35
+ examples = []
36
+ test = [
37
+ "pytest"
38
+ ]
39
+
40
+ [tool.pytest.ini_options]
41
+ pythonpath = [
42
+ "."
43
+ ]
44
+
45
+ [build-system]
46
+ requires = ["hatchling"]
47
+ build-backend = "hatchling.build"
48
+
49
+ [tool.rye]
50
+ managed = true
51
+ dev-dependencies = []
52
+
53
+ [tool.hatch.metadata]
54
+ allow-direct-references = true
55
+
56
+ [tool.hatch.build.targets.wheel]
57
+ packages = ["hyper_connections"]