transfusion-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.
@@ -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,102 @@
1
+ Metadata-Version: 2.3
2
+ Name: transfusion-pytorch
3
+ Version: 0.0.1
4
+ Summary: Transfusion in Pytorch
5
+ Project-URL: Homepage, https://pypi.org/project/transfusion-pytorch/
6
+ Project-URL: Repository, https://github.com/lucidrains/transfusion-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,attention mechanism,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: jaxtyping
40
+ Requires-Dist: rotary-embedding-torch
41
+ Requires-Dist: torch>=2.0
42
+ Description-Content-Type: text/markdown
43
+
44
+ <img src="./transfusion.png" width="400px"></img>
45
+
46
+ ## Transfusion - Pytorch (wip)
47
+
48
+ Pytorch implementation of [Transfusion](https://www.arxiv.org/abs/2408.11039), "Predict the Next Token and Diffuse Images with One Multi-Modal Model", from MetaAI.
49
+
50
+ Once completed, will also extend this to flow matching, as well as audio, video, perhaps even policies.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ $ pip install transfusion-pytorch
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ ```python
61
+ import torch
62
+ from transfusion_pytorch import Transfusion
63
+
64
+ model = Transfusion(
65
+ num_text_tokens = 256,
66
+ transformer = dict(
67
+ dim = 512,
68
+ depth = 8
69
+ )
70
+ )
71
+
72
+ text_ids = torch.randint(0, 256, (1, 1024))
73
+
74
+ modality_tokens = [[
75
+ torch.randn(1, 6, 512),
76
+ torch.randn(1, 4, 512)
77
+ ]]
78
+
79
+ modality_positions = [[
80
+ (2, 6),
81
+ (10, 4)
82
+ ]] # (offset, length)
83
+
84
+ loss, breakdown = model(
85
+ text_ids,
86
+ modality_tokens = modality_tokens,
87
+ modality_positions = modality_positions
88
+ )
89
+
90
+ loss.backward()
91
+ ```
92
+
93
+ ## Citations
94
+
95
+ ```bibtex
96
+ @inproceedings{Zhou2024TransfusionPT,
97
+ title = {Transfusion: Predict the Next Token and Diffuse Images with One Multi-Modal Model},
98
+ author = {Chunting Zhou and Lili Yu and Arun Babu and Kushal Tirumala and Michihiro Yasunaga and Leonid Shamis and Jacob Kahn and Xuezhe Ma and Luke Zettlemoyer and Omer Levy},
99
+ year = {2024},
100
+ url = {https://api.semanticscholar.org/CorpusID:271909855}
101
+ }
102
+ ```
@@ -0,0 +1,59 @@
1
+ <img src="./transfusion.png" width="400px"></img>
2
+
3
+ ## Transfusion - Pytorch (wip)
4
+
5
+ Pytorch implementation of [Transfusion](https://www.arxiv.org/abs/2408.11039), "Predict the Next Token and Diffuse Images with One Multi-Modal Model", from MetaAI.
6
+
7
+ Once completed, will also extend this to flow matching, as well as audio, video, perhaps even policies.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ $ pip install transfusion-pytorch
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ import torch
19
+ from transfusion_pytorch import Transfusion
20
+
21
+ model = Transfusion(
22
+ num_text_tokens = 256,
23
+ transformer = dict(
24
+ dim = 512,
25
+ depth = 8
26
+ )
27
+ )
28
+
29
+ text_ids = torch.randint(0, 256, (1, 1024))
30
+
31
+ modality_tokens = [[
32
+ torch.randn(1, 6, 512),
33
+ torch.randn(1, 4, 512)
34
+ ]]
35
+
36
+ modality_positions = [[
37
+ (2, 6),
38
+ (10, 4)
39
+ ]] # (offset, length)
40
+
41
+ loss, breakdown = model(
42
+ text_ids,
43
+ modality_tokens = modality_tokens,
44
+ modality_positions = modality_positions
45
+ )
46
+
47
+ loss.backward()
48
+ ```
49
+
50
+ ## Citations
51
+
52
+ ```bibtex
53
+ @inproceedings{Zhou2024TransfusionPT,
54
+ title = {Transfusion: Predict the Next Token and Diffuse Images with One Multi-Modal Model},
55
+ author = {Chunting Zhou and Lili Yu and Arun Babu and Kushal Tirumala and Michihiro Yasunaga and Leonid Shamis and Jacob Kahn and Xuezhe Ma and Luke Zettlemoyer and Omer Levy},
56
+ year = {2024},
57
+ url = {https://api.semanticscholar.org/CorpusID:271909855}
58
+ }
59
+ ```
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "transfusion-pytorch"
3
+ version = "0.0.1"
4
+ description = "Transfusion in 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
+ 'attention mechanism',
16
+ 'denoising diffusion',
17
+ ]
18
+ classifiers=[
19
+ 'Development Status :: 4 - Beta',
20
+ 'Intended Audience :: Developers',
21
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
22
+ 'License :: OSI Approved :: MIT License',
23
+ 'Programming Language :: Python :: 3.8',
24
+ ]
25
+
26
+ dependencies = [
27
+ 'einx>=0.3.0',
28
+ 'einops>=0.8.0',
29
+ 'jaxtyping',
30
+ 'rotary_embedding_torch',
31
+ 'torch>=2.0',
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://pypi.org/project/transfusion-pytorch/"
36
+ Repository = "https://github.com/lucidrains/transfusion-pytorch"
37
+
38
+ [build-system]
39
+ requires = ["hatchling"]
40
+ build-backend = "hatchling.build"
41
+
42
+ [tool.rye]
43
+ managed = true
44
+ dev-dependencies = [
45
+ "pytest>=8.2.0",
46
+ ]
47
+
48
+ [tool.hatch.metadata]
49
+ allow-direct-references = true
50
+
51
+ [tool.hatch.build.targets.wheel]
52
+ packages = ["transfusion_pytorch"]
@@ -0,0 +1 @@
1
+ from transfusion_pytorch.transfusion import Transfusion
@@ -0,0 +1,26 @@
1
+ from torch import Tensor
2
+
3
+ from jaxtyping import (
4
+ Float,
5
+ Int,
6
+ Bool
7
+ )
8
+
9
+ # jaxtyping is a misnomer, works for pytorch
10
+
11
+ class TorchTyping:
12
+ def __init__(self, abstract_dtype):
13
+ self.abstract_dtype = abstract_dtype
14
+
15
+ def __getitem__(self, shapes: str):
16
+ return self.abstract_dtype[Tensor, shapes]
17
+
18
+ Float = TorchTyping(Float)
19
+ Int = TorchTyping(Int)
20
+ Bool = TorchTyping(Bool)
21
+
22
+ __all__ = [
23
+ Float,
24
+ Int,
25
+ Bool
26
+ ]
@@ -0,0 +1,607 @@
1
+ from __future__ import annotations
2
+
3
+ """
4
+ global ein notation
5
+
6
+ b - batch
7
+ m - modalities
8
+ n - sequence
9
+ d - dimension
10
+ l - logits (text)
11
+ i, j - sequence (row, col)
12
+ """
13
+
14
+ from functools import partial
15
+ from collections import namedtuple
16
+
17
+ import torch
18
+ from torch import nn, Tensor, tensor
19
+ import torch.nn.functional as F
20
+ from torch.nn import Module, ModuleList
21
+ from torch.nn.utils.rnn import pad_sequence
22
+
23
+ import einx
24
+ from einops import rearrange, repeat, reduce, einsum, pack
25
+ from einops.layers.torch import Rearrange
26
+
27
+ from transfusion_pytorch.tensor_typing import Float, Int, Bool
28
+
29
+ from rotary_embedding_torch import RotaryEmbedding, apply_rotary_emb
30
+
31
+ pad_sequence = partial(pad_sequence, batch_first = True)
32
+
33
+ # constants
34
+
35
+ RawModalityPositions = list[list[tuple[int, int]]]
36
+
37
+ LossBreakdown = namedtuple('LossBreakdown', ['total', 'text', 'diffusion'])
38
+
39
+ # helper functions
40
+
41
+ def exists(v):
42
+ return v is not None
43
+
44
+ def default(v, d):
45
+ return v if exists(v) else d
46
+
47
+ def divisible_by(num, den):
48
+ return (num % den) == 0
49
+
50
+ # tensor helpers
51
+
52
+ def l2norm(t):
53
+ return F.normalize(t, dim = -1)
54
+
55
+ def softclamp(t, value = 50.):
56
+ return (t / value).tanh() * value
57
+
58
+ # flex attention mask construction
59
+ # https://pytorch.org/blog/flexattention/
60
+
61
+ def causal(b, h, q_idx, kv_idx):
62
+ return q_idx >= kv_idx
63
+
64
+ def modality(offset, length):
65
+
66
+ def mask_fn(b, h, q_idx, kv_idx):
67
+ return q_idx >= offset & kv_idx < (offset + length)
68
+
69
+ return mask_fn
70
+
71
+ def transfusion_attn_mask(modalities: list[tuple[int, int]]):
72
+
73
+ def mask_mod(*args):
74
+ is_causal = causal(*args)
75
+
76
+ modality_mask_mods = [modality(*modality_coors_info) for modality_coors_info in modalities]
77
+
78
+ is_modality = any([fn(*args) for fn in modality_mask_mods])
79
+
80
+ return is_causal | is_modality
81
+
82
+ return mask_mod
83
+
84
+ # converting a raw list of modality offsets and lengths to tensor
85
+
86
+ def modality_positions_to_tensor(
87
+ modalities: RawModalityPositions,
88
+ pad_value = 0
89
+ ) -> Int['b m 2']:
90
+
91
+ modalities: list[Tensor] = [tensor(modality) for modality in modalities]
92
+ modalities = pad_sequence(modalities, padding_value = pad_value)
93
+ return modalities
94
+
95
+ # sanitizing modalities tensor, making sure it is ordered
96
+
97
+ def order_modality_positions_by_seq_offset(
98
+ modalities: Int['b m 2']
99
+ ) -> tuple[Int['b m 2'], Int['b m']]:
100
+
101
+ offsets, lengths = modalities.unbind(dim = -1)
102
+
103
+ no_modality_mask = lengths <= 0 # there may be uneven number of modalities per batch sample
104
+ offsets_to_sort = offsets.masked_fill(no_modality_mask, 1e10)
105
+ _, sorted_indices = offsets_to_sort.sort(dim = -1)
106
+
107
+ # sort by ascending offset and do a final mask of both offset and length to 0
108
+
109
+ modalities = einx.get_at('b [mi] ..., b mo -> b mo ...', modalities, sorted_indices)
110
+ modalities = einx.where('b m, b m ..., -> b m ...', ~no_modality_mask, modalities, 0.)
111
+
112
+ return modalities, sorted_indices
113
+
114
+ # deriving relative positions from modality positions
115
+ # ex. given a sequence of 10 with an image at offset 3 with length 4 - [t] [t] [t] [i] [i] [i] [i] [t] [t] [t]
116
+ # relative positions for rotary will be [0] [1] [2] [3] [3] [3] [3] [4] [5] [6]
117
+ # rationale is that each modality will need the same position so there is no distance when conducting bidirectional attention, but should still have a relative distance to other text tokens and modalities
118
+
119
+ def derive_rotary_positions_from_modality_positions(
120
+ seq_len: int,
121
+ modalities: Int['b m 2']
122
+ ) -> Int['b n']:
123
+
124
+ device = modalities.device
125
+
126
+ modality_mask = modality_positions_to_is_modality_mask(seq_len, modalities, offset = torch.tensor([1, -1]))
127
+ is_any_modality = modality_mask.any(dim = 1)
128
+
129
+ return torch.arange(seq_len, device = device) - is_any_modality.cumsum(dim = -1)
130
+
131
+ # modality tokens are given as list of tensors, can be then be embedded into the modality tokens for attending alongside text tokens
132
+
133
+ def embed_modality_tokens(
134
+ seq_len: int,
135
+ dim: int,
136
+ modality_tokens: list[list[Float['b _ d']]],
137
+ modalities: Int['b m 2']
138
+ ) -> Float['b n d']:
139
+
140
+ batch, device = modalities.shape[0], modalities.device
141
+
142
+ output = torch.zeros((batch, seq_len, dim), device = device)
143
+
144
+ for batch_ind, (one_modality, one_modality_token) in enumerate(zip(modalities, modality_tokens)):
145
+ for (offset, length), batch_modality_token in zip(one_modality, one_modality_token):
146
+ if length <= 0:
147
+ continue
148
+ modality_shape = batch_modality_token.shape
149
+
150
+ assert length == modality_shape[1], f'received a modality of shape {modality_shape} but sequence length in modalities info is {length}'
151
+
152
+ output[batch_ind, offset:(offset + length)] = batch_modality_token
153
+
154
+ return output
155
+
156
+ # functions for managing modality token mask
157
+
158
+ def modality_positions_to_is_modality_mask(
159
+ seq_len: int,
160
+ modalities: RawModalityPositions | Int['b m 2'],
161
+ offset: Int['2'] | None = None,
162
+ ) -> Bool['b m n']:
163
+
164
+ if isinstance(modalities, list):
165
+ modalities = modality_positions_to_tensor(modalities)
166
+
167
+ if exists(offset):
168
+ modalities = modalities + offset.to(modalities)
169
+
170
+ left, right = modalities.cumsum(dim = -1).unbind(dim = -1)
171
+
172
+ seq = torch.arange(seq_len, device = modalities.device)
173
+
174
+ is_modality = (
175
+ einx.greater_equal('i, b m -> b m i', seq, left) &
176
+ einx.less('j, b m -> b m j', seq, right)
177
+ )
178
+
179
+ return is_modality
180
+
181
+ def naive_attn_mask(
182
+ seq_len: int,
183
+ modalities: RawModalityPositions | Int['b m 2'],
184
+ device = None
185
+ ) -> Bool['b i j']:
186
+
187
+ if isinstance(modalities, list):
188
+ modalities = modalities_to_tensor(modalities)
189
+
190
+ offsets, length = modalities.unbind(dim = -1)
191
+
192
+ seq = torch.arange(seq_len, device = device)
193
+
194
+ is_causal = einx.greater_equal('i, j -> i j', seq, seq)
195
+
196
+ is_modality = (
197
+ einx.greater_equal('i, b m -> b m i 1', seq, offsets) &
198
+ einx.less('j, b m -> b m 1 j', seq, offsets + length)
199
+ )
200
+
201
+ return is_causal | is_modality.any(dim = 1)
202
+
203
+ # random fourier embedding
204
+
205
+ class RandomFourierEmbed(Module):
206
+ def __init__(self, dim):
207
+ super().__init__()
208
+ assert divisible_by(dim, 2)
209
+ self.dim = dim
210
+ self.register_buffer('weights', torch.randn(dim // 2))
211
+
212
+ def forward(
213
+ self,
214
+ times: Float['b n']
215
+ ) -> Float['b n {self.dim + 1}']:
216
+
217
+ freqs = einx.multiply('... i, j -> ... i j', times, self.weights) * 2 * torch.pi
218
+ fourier_embed, _ = pack((times, freqs.sin(), freqs.cos()), 'b n *')
219
+ return fourier_embed
220
+
221
+ # adaptive layernorm and ada-ln zero rolled into one wrapper
222
+ # from DiT paper and sota for time conditioning for now
223
+
224
+ class AdaptiveWrapper(Module):
225
+ def __init__(
226
+ self,
227
+ fn: Module,
228
+ dim,
229
+ dim_cond,
230
+ ada_ln_zero_init_bias = -2
231
+ ):
232
+ super().__init__()
233
+ self.fn = fn
234
+ self.dim = dim
235
+ self.dim_cond = dim_cond
236
+
237
+ self.layernorm = nn.LayerNorm(dim, elementwise_affine = False)
238
+
239
+ # text will be subjected to normal layernorm bias
240
+ # and for output will use layerscale
241
+
242
+ self.layernorm_gamma = nn.Parameter(torch.zeros(dim))
243
+ self.layerscale = nn.Parameter(torch.ones(dim))
244
+
245
+ # modalities will get the adaptive layernorm + ada-ln zero
246
+
247
+ self.to_film = nn.Linear(dim_cond, dim * 2)
248
+ self.to_ada_ln_zero = nn.Linear(dim_cond, dim)
249
+
250
+ nn.init.zeros_(self.to_film.weight)
251
+ nn.init.zeros_(self.to_ada_ln_zero.weight)
252
+ nn.init.constant_(self.to_ada_ln_zero.bias, ada_ln_zero_init_bias)
253
+
254
+ def forward(
255
+ self,
256
+ x: Float['b n {self.dim}'],
257
+ cond: Float['b {self.dim_cond}'] | Float['b n {self.dim_cond}'],
258
+ is_any_modality: Bool['b n'],
259
+ **kwargs
260
+ ):
261
+ is_any_modality = rearrange(is_any_modality, '... -> ... 1')
262
+
263
+ if cond.ndim == 2:
264
+ cond = rearrange(cond, 'b d -> b 1 d')
265
+
266
+ x = self.layernorm(x)
267
+
268
+ gamma, beta = self.to_film(cond).chunk(2, dim = -1)
269
+
270
+ text_tokens = x * (self.layernorm_gamma + 1.)
271
+ modality_tokens = x * (gamma + 1.) + beta
272
+
273
+ x = torch.where(is_any_modality, modality_tokens, text_tokens)
274
+
275
+ # attention or feedforwards
276
+
277
+ out = self.fn(x, **kwargs)
278
+
279
+ # take care of conditioning output separately for text vs modality
280
+
281
+ text_out = out * self.layerscale
282
+ modalities_out = out * self.to_ada_ln_zero(cond).sigmoid()
283
+
284
+ return torch.where(is_any_modality, modalities_out, text_out)
285
+
286
+ # attention
287
+
288
+ class RMSNorm(Module):
289
+ def __init__(self, dim):
290
+ super().__init__()
291
+ self.scale = dim ** 0.5
292
+ self.gamma = nn.Parameter(torch.zeros(dim))
293
+
294
+ def forward(self, x):
295
+ return l2norm(x) * self.scale * (self.gamma + 1.) # use unit offset from Ohad Rubin
296
+
297
+ class GEGLU(Module):
298
+ def forward(self, x):
299
+ x, gates = x.chunk(2, dim = -1)
300
+ return F.gelu(gates) * x
301
+
302
+ def FeedForward(
303
+ dim,
304
+ expansion_factor = 4.,
305
+ dropout = 0.
306
+ ):
307
+ dim_inner = int(dim * expansion_factor * 2 / 3)
308
+ return nn.Sequential(
309
+ RMSNorm(dim),
310
+ nn.Linear(dim, dim_inner * 2),
311
+ GEGLU(),
312
+ nn.Dropout(dropout),
313
+ nn.Linear(dim_inner, dim)
314
+ )
315
+
316
+ class Attention(Module):
317
+ def __init__(
318
+ self,
319
+ dim,
320
+ dim_head = 64,
321
+ heads = 8,
322
+ dropout = 0.,
323
+ softcap_value = 50.,
324
+ ):
325
+ super().__init__()
326
+ self.scale = dim_head ** -0.5
327
+ dim_inner = dim_head * heads
328
+
329
+ self.norm = RMSNorm(dim)
330
+
331
+ self.to_qkv = nn.Sequential(
332
+ nn.Linear(dim, dim_inner * 3, bias = False),
333
+ Rearrange('b n (qkv h d) -> qkv b h n d', qkv = 3, h = heads)
334
+ )
335
+
336
+ self.softcap_value = softcap_value
337
+
338
+ self.dropout = nn.Dropout(dropout)
339
+
340
+ self.to_out = nn.Sequential(
341
+ Rearrange('b h n d -> b n (h d)'),
342
+ nn.Linear(dim_inner, dim, bias = False)
343
+ )
344
+
345
+ def forward(
346
+ self,
347
+ x,
348
+ attn_mask = None,
349
+ rotary_emb: Tensor | None = None
350
+ ):
351
+ x = self.norm(x)
352
+
353
+ q, k, v = self.to_qkv(x)
354
+
355
+ if exists(rotary_emb):
356
+ q, k = tuple(apply_rotary_emb(rotary_emb, t) for t in (q, k))
357
+
358
+ q = q * self.scale
359
+ sim = einsum(q, k, 'b h i d, b h j d -> b h i j')
360
+
361
+ sim = softclamp(sim, self.softcap_value)
362
+
363
+ if exists(attn_mask):
364
+ mask_value = -torch.finfo(sim.dtype).max
365
+ sim = einx.where('b i j, b h i j, -> b h i j', attn_mask, sim, mask_value)
366
+
367
+ attn = sim.softmax(dim = -1)
368
+
369
+ attn = self.dropout(attn)
370
+
371
+ out = einsum(attn, v, 'b h i j, b h j d -> b h i d')
372
+
373
+ return self.to_out(out)
374
+
375
+ class Transformer(Module):
376
+ def __init__(
377
+ self,
378
+ dim,
379
+ *,
380
+ depth,
381
+ dim_head = 64,
382
+ heads = 8,
383
+ dropout = 0.,
384
+ ff_expansion_factor = 4,
385
+ attn_kwargs: dict = dict(),
386
+ ff_kwargs: dict = dict()
387
+ ):
388
+ super().__init__()
389
+ self.dim = dim
390
+ self.dim_head = dim_head
391
+
392
+ self.to_time_cond = nn.Sequential(
393
+ RandomFourierEmbed(dim),
394
+ nn.Linear(dim + 1, dim * 4),
395
+ nn.SiLU()
396
+ )
397
+
398
+ layers = ModuleList([])
399
+
400
+ for _ in range(depth):
401
+ attn = Attention(dim = dim, dim_head = dim_head, heads = heads, dropout = dropout, **attn_kwargs)
402
+
403
+ ff = FeedForward(dim = dim, expansion_factor = ff_expansion_factor, **ff_kwargs)
404
+
405
+ attn = AdaptiveWrapper(attn, dim = dim, dim_cond = dim * 4)
406
+ ff = AdaptiveWrapper(ff, dim = dim, dim_cond = dim * 4)
407
+
408
+ layers.append(ModuleList([attn, ff]))
409
+
410
+ self.layers = layers
411
+ self.norm = RMSNorm(dim)
412
+
413
+ def forward(
414
+ self,
415
+ x,
416
+ times: Float[''] | Float['b'] | Float['b n'],
417
+ attn_mask: Bool['b i j'] | None = None,
418
+ modality_positions: RawModalityPositions | Int['b n 2'] | None = None,
419
+ is_any_modality: Bool['b n'] | None = None,
420
+ rotary_emb: Tensor | None = None
421
+ ):
422
+ seq_len, device = x.shape[-2], x.device
423
+ assert exists(attn_mask) ^ exists(modality_positions)
424
+
425
+ # handle time
426
+
427
+ if times.ndim == 0:
428
+ times = repeat(times, ' -> b', b = batch)
429
+
430
+ cond = self.to_time_cond(times)
431
+
432
+ # create the specialized mask needed for autoregressive text + bidirectional diffusion attention
433
+
434
+ if exists(modality_positions):
435
+ attn_mask = naive_attn_mask(seq_len, modality_positions, device = device)
436
+
437
+ if not exists(is_any_modality):
438
+ assert exists(modality_positions)
439
+ is_any_modality = modality_positions_to_is_modality_mask(seq_len, modality_positions).any(dim = 1)
440
+
441
+ adaptive_kwargs = dict(cond = cond, is_any_modality = is_any_modality)
442
+
443
+ # transformer layers as usual, using mask from above
444
+
445
+ for attn, ff in self.layers:
446
+ x = attn(x, attn_mask = attn_mask, rotary_emb = rotary_emb, **adaptive_kwargs) + x
447
+ x = ff(x, **adaptive_kwargs) + x
448
+
449
+ return self.norm(x)
450
+
451
+ # classes
452
+
453
+ class Transfusion(Module):
454
+ def __init__(
455
+ self,
456
+ *,
457
+ num_text_tokens,
458
+ transformer: dict | Transformer,
459
+ ignore_index = -1,
460
+ diffusion_loss_weight = 1.
461
+ ):
462
+ super().__init__()
463
+
464
+ # transformer
465
+
466
+ if isinstance(transformer, dict):
467
+ transformer = Transformer(**transformer)
468
+
469
+ self.transformer = transformer
470
+ dim, dim_head = transformer.dim, transformer.dim_head
471
+ self.dim = dim
472
+
473
+ # relative positions
474
+
475
+ self.rotary_emb = RotaryEmbedding(transformer.dim_head)
476
+
477
+ # embeddings and un-embeddings
478
+
479
+ self.text_embed = nn.Embedding(num_text_tokens, dim)
480
+
481
+ self.to_text_logits = nn.Linear(dim, num_text_tokens, bias = False)
482
+
483
+ self.to_pred_flow = nn.Linear(dim, dim, bias = False)
484
+
485
+ # loss related
486
+
487
+ self.ignore_index = ignore_index
488
+ self.diffusion_loss_weight = diffusion_loss_weight
489
+
490
+ def forward(
491
+ self,
492
+ text: Int['b n'],
493
+ modality_tokens: list[list[Float['b _ d']]] | Float['b n d'],
494
+ modality_positions: RawModalityPositions | Int['b m 2'],
495
+ times: Int['b'] | None = None,
496
+ return_loss = True
497
+ ) -> (
498
+ Float['b n l'] |
499
+ tuple[Float[''], LossBreakdown]
500
+ ):
501
+
502
+ # if returning loss, split text for next token prediction
503
+
504
+ if return_loss:
505
+ text, text_labels = text[:, :-1], text[:, 1:]
506
+
507
+ # derive is_modality mask for diffusion on the right tokens + diffusion loss
508
+
509
+ batch, seq_len, device = *text.shape, text.device
510
+
511
+ assert len(modality_positions) == batch
512
+
513
+ if isinstance(modality_positions, list):
514
+ modality_positions = modality_positions_to_tensor(modality_positions)
515
+
516
+ # embed the list of modality tokens into a sequence of Float['b n d'] at right offsets and lengths as dictated by modalities info tensor
517
+
518
+ if isinstance(modality_tokens, list):
519
+ modality_tokens = embed_modality_tokens(seq_len, self.dim, modality_tokens, modality_positions)
520
+
521
+ # sort the modalities tensor and sanitize, readying for noising of modalities
522
+
523
+ modality_positions, sorted_indices = order_modality_positions_by_seq_offset(modality_positions)
524
+
525
+ num_modalities = modality_positions.shape[-2]
526
+
527
+ is_modalities = modality_positions_to_is_modality_mask(seq_len, modality_positions)
528
+
529
+ is_any_modality = reduce(is_modalities, 'b m n -> b n', 'any')
530
+
531
+ # embed text
532
+
533
+ text_tokens = self.text_embed(text)
534
+
535
+ # noise the modality tokens
536
+
537
+ if not exists(times):
538
+ times = torch.rand((batch, num_modalities), device = device)
539
+
540
+ if return_loss:
541
+ times = einsum(is_modalities.float(), times, 'b m n, b m -> b n')
542
+ padded_times = rearrange(times, 'b n -> b n 1')
543
+ noise = torch.randn_like(modality_tokens)
544
+
545
+ modality_tokens = modality_tokens * padded_times + noise * (1. - padded_times)
546
+
547
+ # the flow is the (data - noise)
548
+
549
+ flow = modality_tokens - noise
550
+
551
+ # intersperse the modalities with the text for the joint transformer + diffusion system
552
+
553
+ tokens = einx.where('b n, b n d, b n d', is_any_modality, modality_tokens, text_tokens)
554
+
555
+ # derive rotary positions
556
+
557
+ rotary_positions = derive_rotary_positions_from_modality_positions(seq_len, modality_positions)
558
+
559
+ rotary_emb = self.rotary_emb(rotary_positions)
560
+
561
+ # attention
562
+
563
+ embed = self.transformer(
564
+ tokens,
565
+ times = times,
566
+ rotary_emb = rotary_emb,
567
+ modality_positions = modality_positions
568
+ )
569
+
570
+ # text unembedding
571
+
572
+ text_logits = self.to_text_logits(embed)
573
+
574
+ if not return_loss:
575
+ return text_logits
576
+
577
+ # text autoregressive loss
578
+
579
+ text_loss = F.cross_entropy(
580
+ rearrange(text_logits, 'b n l -> b l n'),
581
+ text_labels,
582
+ ignore_index = self.ignore_index,
583
+ reduction = 'none'
584
+ )
585
+
586
+ text_loss = text_loss[~is_any_modality].mean()
587
+
588
+ # diffusion loss
589
+
590
+ pred_flow = self.to_pred_flow(embed)
591
+
592
+ diffusion_loss = F.mse_loss(
593
+ pred_flow,
594
+ flow,
595
+ reduction = 'none'
596
+ )
597
+
598
+ diffusion_loss = diffusion_loss[is_any_modality].mean()
599
+
600
+ # only the token positions that are not modalities have autoregressive loss
601
+
602
+ total_loss = (
603
+ text_loss +
604
+ diffusion_loss * self.diffusion_loss_weight
605
+ )
606
+
607
+ return total_loss, LossBreakdown(total_loss, text_loss, diffusion_loss)