hanghang214 commited on
Commit
ccdb058
·
verified ·
1 Parent(s): 7437fae

upload-required-gafl-dependency

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. gafl/.gitignore +211 -0
  2. gafl/AUTHORS.md +6 -0
  3. gafl/LICENSE +57 -0
  4. gafl/NOTICE.md +2 -0
  5. gafl/README.md +87 -0
  6. gafl/build/geometric-algebra-transformer/.coveragerc +2 -0
  7. gafl/build/geometric-algebra-transformer/.dockerignore +9 -0
  8. gafl/build/geometric-algebra-transformer/.gitignore +9 -0
  9. gafl/build/geometric-algebra-transformer/.pylintrc +638 -0
  10. gafl/build/geometric-algebra-transformer/CHANGELOG.md +36 -0
  11. gafl/build/geometric-algebra-transformer/GATr.egg-info/PKG-INFO +27 -0
  12. gafl/build/geometric-algebra-transformer/GATr.egg-info/SOURCES.txt +80 -0
  13. gafl/build/geometric-algebra-transformer/GATr.egg-info/dependency_links.txt +1 -0
  14. gafl/build/geometric-algebra-transformer/GATr.egg-info/requires.txt +5 -0
  15. gafl/build/geometric-algebra-transformer/GATr.egg-info/top_level.txt +1 -0
  16. gafl/build/geometric-algebra-transformer/LICENSE +13 -0
  17. gafl/build/geometric-algebra-transformer/README.md +394 -0
  18. gafl/build/geometric-algebra-transformer/build/lib/gatr/__init__.py +8 -0
  19. gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/__init__.py +4 -0
  20. gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/gcan.py +299 -0
  21. gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/mlp.py +40 -0
  22. gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/segnn.py +110 -0
  23. gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/transformer.py +557 -0
  24. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/__init__.py +4 -0
  25. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/__init__.py +5 -0
  26. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/dataset.py +55 -0
  27. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/experiment.py +259 -0
  28. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/wrappers.py +153 -0
  29. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_experiment.py +774 -0
  30. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_wrapper.py +142 -0
  31. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/__init__.py +11 -0
  32. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/dataset.py +76 -0
  33. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/experiment.py +99 -0
  34. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/simulator.py +223 -0
  35. gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/wrappers.py +489 -0
  36. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/__init__.py +15 -0
  37. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/object.py +212 -0
  38. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/plane.py +72 -0
  39. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/point.py +104 -0
  40. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/pseudoscalar.py +44 -0
  41. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/reflection.py +56 -0
  42. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/rotation.py +75 -0
  43. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/scalar.py +44 -0
  44. gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/translation.py +83 -0
  45. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/__init__.py +11 -0
  46. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/__init__.py +4 -0
  47. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/attention.py +92 -0
  48. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/config.py +106 -0
  49. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/positional_encoding.py +131 -0
  50. gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/qkv.py +209 -0
gafl/.gitignore ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wandb/
2
+ wandb*.json
3
+ **/*.ckpt
4
+ **/*.pth
5
+ **/*.json
6
+ .vscode/
7
+ **/*.pdb
8
+ ckpt/
9
+ *.code-workspace
10
+ outputs/
11
+ **/*.txt
12
+ **/lightning_logs/
13
+ **/inference_outputs/
14
+ .hydra
15
+ scope_preprocessed/
16
+ preprocessed/
17
+ datasets/
18
+ *.zip
19
+
20
+ # job.sh
21
+
22
+ slurm_logs/*
23
+ *.csv
24
+
25
+ # Byte-compiled / optimized / DLL files
26
+ __pycache__/
27
+ *.py[cod]
28
+ *$py.class
29
+
30
+ # C extensions
31
+ *.so
32
+
33
+ # Distribution / packaging
34
+ .Python
35
+ build/
36
+ develop-eggs/
37
+ dist/
38
+ downloads/
39
+ eggs/
40
+ .eggs/
41
+ lib/
42
+ lib64/
43
+ parts/
44
+ sdist/
45
+ var/
46
+ wheels/
47
+ share/python-wheels/
48
+ *.egg-info/
49
+ .installed.cfg
50
+ *.egg
51
+ MANIFEST
52
+
53
+ # PyInstaller
54
+ # Usually these files are written by a python script from a template
55
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
56
+ *.manifest
57
+ *.spec
58
+
59
+ # Installer logs
60
+ pip-log.txt
61
+ pip-delete-this-directory.txt
62
+
63
+ # Unit test / coverage reports
64
+ htmlcov/
65
+ .tox/
66
+ .nox/
67
+ .coverage
68
+ .coverage.*
69
+ .cache
70
+ nosetests.xml
71
+ coverage.xml
72
+ *.cover
73
+ *.py,cover
74
+ .hypothesis/
75
+ .pytest_cache/
76
+ cover/
77
+
78
+ # Translations
79
+ *.mo
80
+ *.pot
81
+
82
+ # Django stuff:
83
+ *.log
84
+ local_settings.py
85
+ db.sqlite3
86
+ db.sqlite3-journal
87
+
88
+ # Flask stuff:
89
+ instance/
90
+ .webassets-cache
91
+
92
+ # Scrapy stuff:
93
+ .scrapy
94
+
95
+ # Sphinx documentation
96
+ docs/_build/
97
+
98
+ # PyBuilder
99
+ .pybuilder/
100
+ target/
101
+
102
+ # Jupyter Notebook
103
+ .ipynb_checkpoints
104
+
105
+ # IPython
106
+ profile_default/
107
+ ipython_config.py
108
+
109
+ # pyenv
110
+ # For a library or package, you might want to ignore these files since the code is
111
+ # intended to run in multiple environments; otherwise, check them in:
112
+ # .python-version
113
+
114
+ # pipenv
115
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
116
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
117
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
118
+ # install all needed dependencies.
119
+ #Pipfile.lock
120
+
121
+ # poetry
122
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
123
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
124
+ # commonly ignored for libraries.
125
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
126
+ #poetry.lock
127
+
128
+ # pdm
129
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
130
+ #pdm.lock
131
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
132
+ # in version control.
133
+ # https://pdm.fming.dev/#use-with-ide
134
+ .pdm.toml
135
+
136
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
137
+ __pypackages__/
138
+
139
+ # Celery stuff
140
+ celerybeat-schedule
141
+ celerybeat.pid
142
+
143
+ # SageMath parsed files
144
+ *.sage.py
145
+
146
+ # Environments
147
+ .env
148
+ .venv
149
+ env/
150
+ venv/
151
+ ENV/
152
+ env.bak/
153
+ venv.bak/
154
+
155
+ # Spyder project settings
156
+ .spyderproject
157
+ .spyproject
158
+
159
+ # Rope project settings
160
+ .ropeproject
161
+
162
+ # mkdocs documentation
163
+ /site
164
+
165
+ # mypy
166
+ .mypy_cache/
167
+ .dmypy.json
168
+ dmypy.json
169
+
170
+ # Pyre type checker
171
+ .pyre/
172
+
173
+ # pytype static type analyzer
174
+ .pytype/
175
+
176
+ # Cython debug symbols
177
+ cython_debug/
178
+
179
+ # PyCharm
180
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
181
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
182
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
183
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
184
+ #.idea/
185
+ configs/hybrid_cascade.yaml
186
+ plots/
187
+ test.py
188
+ ATLAS/
189
+ *.sh
190
+ !install_gatr.sh
191
+ tmp/
192
+ databases/
193
+ dataset-*
194
+ outputs/
195
+
196
+
197
+ scripts/logs/
198
+ results/
199
+
200
+ # exclude .sh and .csv in scripts from gitignore:
201
+ !scripts/*.sh
202
+ !scripts/*.csv
203
+ metrics.csv
204
+
205
+ notebooks/*.png
206
+ tensors/a.pt
207
+ tensors/o_pt.pt
208
+
209
+ configs/data/
210
+ .condarc
211
+ log
gafl/AUTHORS.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Simon Wagner
2
+ Leif Seute
3
+ Vsevolod Viliuga
4
+ Nicolas Wolf
5
+ Frauke Gräter
6
+ Jan Stühmer
gafl/LICENSE ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation
2
+ Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH
3
+
4
+ Based on the code for
5
+
6
+ Fast protein backbone generation with SE(3) flow matching
7
+ Copyright (c) Microsoft Corporation
8
+
9
+ and
10
+
11
+ Geometric Algebra Transformer
12
+ Copyright (c) 2023 Qualcomm Technologies, Inc.
13
+
14
+ -----------------------------------------------------------------------------
15
+ MIT license
16
+
17
+ applies to
18
+
19
+ Fast protein backbone generation with SE(3) flow matching
20
+ Copyright (c) Microsoft Corporation
21
+
22
+ Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation
23
+ Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH
24
+
25
+ i.e. to all code in this repository except gafl/models/gafl/pga_utils.py.
26
+ -----------------------------------------------------------------------------
27
+
28
+
29
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
30
+
31
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
32
+
33
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34
+
35
+
36
+ -----------------------------------------------------------------------------
37
+ 3-Clause BSD License
38
+
39
+ applies to derivative work based on
40
+
41
+ Geometric Algebra Transformer
42
+ Copyright (c) 2023 Qualcomm Technologies, Inc.
43
+
44
+ i.e. to gafl/models/gafl/pga_utils.py.
45
+
46
+ Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH
47
+ -----------------------------------------------------------------------------
48
+
49
+ Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
50
+
51
+ * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer:
52
+
53
+ * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
54
+
55
+ * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
56
+
57
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
gafl/NOTICE.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ This project includes software from OpenFold (Apache 2.0)
2
+ https://github.com/aqlaboratory/openfold
gafl/README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation
2
+
3
+ Source code for "Generating Highly Designable Proteins with Geometric Algebra Flow Matching" (https://arxiv.org/abs/2411.05238)
4
+
5
+ If you use this code, please cite:
6
+
7
+ ```
8
+ @inproceedings{wagnerseute2024gafl,
9
+ title={Generating Highly Designable Proteins with Geometric Algebra Flow Matching},
10
+ author={Wagner, Simon and Seute, Leif and Viliuga, Vsevolod and Wolf, Nicolas and Gr{\"a}ter, Frauke and St{\"u}hmer, Jan},
11
+ booktitle={Thirty-eighth Conference on Neural Information Processing Systems},
12
+ year={2024}
13
+ }
14
+ ```
15
+
16
+ This repository is based on FrameFlow (https://github.com/microsoft/protein-frame-flow).
17
+
18
+ The datasets and weights of the models reported in the paper will be made available in the future
19
+
20
+ # Installation
21
+
22
+ ### TLDR
23
+
24
+ ```bash
25
+ conda env create -f environment.yaml
26
+ conda activate gafl
27
+ bash install_gatr.sh # Apply patches to gatr
28
+
29
+ # Install package:
30
+ pip install -e .
31
+ ```
32
+
33
+ ### Geometric Algebra Transformer
34
+ Geometric Algebra Transformer (gatr) in version 1.2.0 requires the xformers package that resulted in conflicting package dependencies. We therefore require to install gatr from source and apply patches to remove the dependency on xformers. Please note that gatr is distributed under its own license, which you can find in LICENSE.
35
+
36
+ To install gatr with the required patches please run
37
+ ```
38
+ conda activate gafl
39
+ bash install_gatr.sh
40
+ ```
41
+
42
+ ### Install package
43
+ After installing the requirements from `environment.yaml` or `minimal_env.yaml` and applying the patches to gatr, you can install the `gafl` package by running
44
+ ```bash
45
+ pip install -e .
46
+ ```
47
+
48
+ # Usage
49
+
50
+ ## Inference
51
+
52
+ To sample backbone structures using the model (without the re-folding procedure, which is implemented e.g. in [FrameDiff](https://github.com/jasonkyuyim/se3_diffusion)), run
53
+ ```bash
54
+ python experiments/inference.py inference.ckpt_path=<path/to/ckpt>
55
+ ```
56
+
57
+ You can specify the inference settings like the number of samples and timesteps via a config file like `configs/inference.yaml`.
58
+
59
+ ### Download model weights
60
+
61
+ The weights of the models reported in the paper are published at `https://github.com/hits-mli/gafl/releases/download/v1.0.0/gafl-pdb.zip`. Download the zip file, extract it and specify the path to the checkpoint in the inference command:
62
+ ```bash
63
+ mkdir -p outputs
64
+ wget https://github.com/hits-mli/gafl/releases/download/v1.0.0/gafl-pdb.zip
65
+ unzip gafl-pdb.zip -d outputs
66
+ python experiments/inference.py inference.ckpt_path=outputs/gafl-pdb/gafl321.ckpt
67
+ ```
68
+
69
+
70
+
71
+ ## Training
72
+
73
+ To train the model on the scope dataset, paste the path to your metadata csv file in configs/data/default.yaml and run
74
+
75
+ ```bash
76
+ python experiments/train.py model=gafl
77
+ ```
78
+
79
+ For training on pdb, set paths to the metadata csv file and to the cluster-defining file (as in FrameDiff) in configs/data/pdb.yaml and run
80
+
81
+ ```bash
82
+ python experiments/train.py model=gafl data=pdb
83
+ ```
84
+
85
+ ### Download dataset
86
+
87
+ GAFL was trained on the [PDB dataset from FrameDiff](https://github.com/jasonkyuyim/se3_diffusion?tab=readme-ov-file#downloading-the-pdb-for-training). For ablations, the [SCOPe dataset from FrameFlow](https://github.com/microsoft/protein-frame-flow/tree/legacy?tab=readme-ov-file#data) was used.
gafl/build/geometric-algebra-transformer/.coveragerc ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [run]
2
+ omit = tests/*,scripts/*,gatr/experiments/*
gafl/build/geometric-algebra-transformer/.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # pytest
2
+ .coverage
3
+ .pytest
4
+ .pytest_cache
5
+
6
+ # Python
7
+ *__pycache__*
8
+ *.egg-info
9
+ *.py[cod]
gafl/build/geometric-algebra-transformer/.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # pytest
2
+ .coverage
3
+ .pytest
4
+ .pytest_cache
5
+
6
+ # Python
7
+ *__pycache__*
8
+ *.egg-info
9
+ *.py[cod]
gafl/build/geometric-algebra-transformer/.pylintrc ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .pylintrc generated on 2023-01-19 with pylint 2.15.10
2
+
3
+ [MAIN]
4
+
5
+ # Analyse import fallback blocks. This can be used to support both Python 2 and
6
+ # 3 compatible code, which means that the block might have code that exists
7
+ # only in one or another interpreter, leading to false positives when analysed.
8
+ analyse-fallback-blocks=no
9
+
10
+ # Load and enable all available extensions. Use --list-extensions to see a list
11
+ # all available extensions.
12
+ #enable-all-extensions=
13
+
14
+ # In error mode, messages with a category besides ERROR or FATAL are
15
+ # suppressed, and no reports are done by default. Error mode is compatible with
16
+ # disabling specific errors.
17
+ #errors-only=
18
+
19
+ # Always return a 0 (non-error) status code, even if lint errors are found.
20
+ # This is primarily useful in continuous integration scripts.
21
+ #exit-zero=
22
+
23
+ # A comma-separated list of package or module names from where C extensions may
24
+ # be loaded. Extensions are loading into the active Python interpreter and may
25
+ # run arbitrary code.
26
+ extension-pkg-allow-list=
27
+
28
+ # A comma-separated list of package or module names from where C extensions may
29
+ # be loaded. Extensions are loading into the active Python interpreter and may
30
+ # run arbitrary code. (This is an alternative name to extension-pkg-allow-list
31
+ # for backward compatibility.)
32
+ extension-pkg-whitelist=
33
+
34
+ # Return non-zero exit code if any of these messages/categories are detected,
35
+ # even if score is above --fail-under value. Syntax same as enable. Messages
36
+ # specified are enabled, while categories only check already-enabled messages.
37
+ fail-on=
38
+
39
+ # Specify a score threshold under which the program will exit with error.
40
+ fail-under=10
41
+
42
+ # Interpret the stdin as a python script, whose filename needs to be passed as
43
+ # the module_or_package argument.
44
+ #from-stdin=
45
+
46
+ # Files or directories to be skipped. They should be base names, not paths.
47
+ ignore=CVS,data
48
+
49
+ # Add files or directories matching the regular expressions patterns to the
50
+ # ignore-list. The regex matches against paths and can be in Posix or Windows
51
+ # format. Because '\' represents the directory delimiter on Windows systems, it
52
+ # can't be used as an escape character.
53
+ ignore-paths=notebooks, docker
54
+
55
+ # Files or directories matching the regular expression patterns are skipped.
56
+ # The regex matches against base names, not paths. The default value ignores
57
+ # Emacs file locks
58
+ ignore-patterns=^\.#
59
+
60
+ # List of module names for which member attributes should not be checked
61
+ # (useful for modules/projects where namespaces are manipulated during runtime
62
+ # and thus existing member attributes cannot be deduced by static analysis). It
63
+ # supports qualified module names, as well as Unix pattern matching.
64
+ ignored-modules=
65
+
66
+ # Python code to execute, usually for sys.path manipulation such as
67
+ # pygtk.require().
68
+ #init-hook=
69
+
70
+ # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
71
+ # number of processors available to use, and will cap the count on Windows to
72
+ # avoid hangs.
73
+ jobs=1
74
+
75
+ # Control the amount of potential inferred values when inferring a single
76
+ # object. This can help the performance when dealing with large functions or
77
+ # complex, nested conditions.
78
+ limit-inference-results=100
79
+
80
+ # List of plugins (as comma separated values of python module names) to load,
81
+ # usually to register additional checkers.
82
+ load-plugins=pylint.extensions.docparams
83
+
84
+ # Pickle collected data for later comparisons.
85
+ persistent=yes
86
+
87
+ # Minimum Python version to use for version dependent checks. Will default to
88
+ # the version used to run pylint.
89
+ py-version=3.8
90
+
91
+ # Discover python modules and packages in the file system subtree.
92
+ recursive=no
93
+
94
+ # When enabled, pylint would attempt to guess common misconfiguration and emit
95
+ # user-friendly hints instead of false-positive error messages.
96
+ suggestion-mode=yes
97
+
98
+ # Allow loading of arbitrary C extensions. Extensions are imported into the
99
+ # active Python interpreter and may run arbitrary code.
100
+ unsafe-load-any-extension=no
101
+
102
+ # In verbose mode, extra non-checker-related info will be displayed.
103
+ #verbose=
104
+
105
+
106
+ [BASIC]
107
+
108
+ # Naming style matching correct argument names.
109
+ argument-naming-style=snake_case
110
+
111
+ # Regular expression matching correct argument names. Overrides argument-
112
+ # naming-style. If left empty, argument names will be checked with the set
113
+ # naming style.
114
+ #argument-rgx=
115
+
116
+ # Naming style matching correct attribute names.
117
+ attr-naming-style=snake_case
118
+
119
+ # Regular expression matching correct attribute names. Overrides attr-naming-
120
+ # style. If left empty, attribute names will be checked with the set naming
121
+ # style.
122
+ #attr-rgx=
123
+
124
+ # Bad variable names which should always be refused, separated by a comma.
125
+ bad-names=foo,
126
+ bar,
127
+ baz,
128
+ toto,
129
+ tutu,
130
+ tata
131
+
132
+ # Bad variable names regexes, separated by a comma. If names match any regex,
133
+ # they will always be refused
134
+ bad-names-rgxs=
135
+
136
+ # Naming style matching correct class attribute names.
137
+ class-attribute-naming-style=any
138
+
139
+ # Regular expression matching correct class attribute names. Overrides class-
140
+ # attribute-naming-style. If left empty, class attribute names will be checked
141
+ # with the set naming style.
142
+ #class-attribute-rgx=
143
+
144
+ # Naming style matching correct class constant names.
145
+ class-const-naming-style=UPPER_CASE
146
+
147
+ # Regular expression matching correct class constant names. Overrides class-
148
+ # const-naming-style. If left empty, class constant names will be checked with
149
+ # the set naming style.
150
+ #class-const-rgx=
151
+
152
+ # Naming style matching correct class names.
153
+ class-naming-style=PascalCase
154
+
155
+ # Regular expression matching correct class names. Overrides class-naming-
156
+ # style. If left empty, class names will be checked with the set naming style.
157
+ #class-rgx=
158
+
159
+ # Naming style matching correct constant names.
160
+ const-naming-style=UPPER_CASE
161
+
162
+ # Regular expression matching correct constant names. Overrides const-naming-
163
+ # style. If left empty, constant names will be checked with the set naming
164
+ # style.
165
+ #const-rgx=
166
+
167
+ # Minimum line length for functions/classes that require docstrings, shorter
168
+ # ones are exempt.
169
+ docstring-min-length=-1
170
+
171
+ # Naming style matching correct function names.
172
+ function-naming-style=snake_case
173
+
174
+ # Regular expression matching correct function names. Overrides function-
175
+ # naming-style. If left empty, function names will be checked with the set
176
+ # naming style.
177
+ #function-rgx=
178
+
179
+ # Good variable names which should always be accepted, separated by a comma.
180
+ good-names=i,
181
+ j,
182
+ k,
183
+ x,
184
+ y,
185
+ z,
186
+ h,
187
+ ex,
188
+ Run,
189
+ _
190
+
191
+ # Good variable names regexes, separated by a comma. If names match any regex,
192
+ # they will always be accepted
193
+ good-names-rgxs=
194
+
195
+ # Include a hint for the correct naming format with invalid-name.
196
+ include-naming-hint=yes
197
+
198
+ # Naming style matching correct inline iteration names.
199
+ inlinevar-naming-style=any
200
+
201
+ # Regular expression matching correct inline iteration names. Overrides
202
+ # inlinevar-naming-style. If left empty, inline iteration names will be checked
203
+ # with the set naming style.
204
+ #inlinevar-rgx=
205
+
206
+ # Naming style matching correct method names.
207
+ method-naming-style=snake_case
208
+
209
+ # Regular expression matching correct method names. Overrides method-naming-
210
+ # style. If left empty, method names will be checked with the set naming style.
211
+ #method-rgx=
212
+
213
+ # Naming style matching correct module names.
214
+ module-naming-style=snake_case
215
+
216
+ # Regular expression matching correct module names. Overrides module-naming-
217
+ # style. If left empty, module names will be checked with the set naming style.
218
+ #module-rgx=
219
+
220
+ # Colon-delimited sets of names that determine each other's naming style when
221
+ # the name regexes allow several styles.
222
+ name-group=
223
+
224
+ # Regular expression which should only match function or class names that do
225
+ # not require a docstring.
226
+ no-docstring-rgx=^_
227
+
228
+ # List of decorators that produce properties, such as abc.abstractproperty. Add
229
+ # to this list to register other decorators that produce valid properties.
230
+ # These decorators are taken in consideration only for invalid-name.
231
+ property-classes=abc.abstractproperty
232
+
233
+ # Regular expression matching correct type variable names. If left empty, type
234
+ # variable names will be checked with the set naming style.
235
+ #typevar-rgx=
236
+
237
+ # Naming style matching correct variable names.
238
+ variable-naming-style=snake_case
239
+
240
+ # Regular expression matching correct variable names. Overrides variable-
241
+ # naming-style. If left empty, variable names will be checked with the set
242
+ # naming style.
243
+ #variable-rgx=
244
+
245
+
246
+ [CLASSES]
247
+
248
+ # Warn about protected attribute access inside special methods
249
+ check-protected-access-in-special-methods=no
250
+
251
+ # List of method names used to declare (i.e. assign) instance attributes.
252
+ defining-attr-methods=__init__,
253
+ __new__,
254
+ setUp,
255
+ __post_init__
256
+
257
+ # List of member names, which should be excluded from the protected access
258
+ # warning.
259
+ exclude-protected=_asdict,
260
+ _fields,
261
+ _replace,
262
+ _source,
263
+ _make,
264
+ _calculate_fan_in_and_fan_out,
265
+ _target_
266
+
267
+ # List of valid names for the first argument in a class method.
268
+ valid-classmethod-first-arg=cls
269
+
270
+ # List of valid names for the first argument in a metaclass class method.
271
+ valid-metaclass-classmethod-first-arg=cls
272
+
273
+
274
+ [DESIGN]
275
+
276
+ # List of regular expressions of class ancestor names to ignore when counting
277
+ # public methods (see R0903)
278
+ exclude-too-few-public-methods=
279
+
280
+ # List of qualified class names to ignore when counting class parents (see
281
+ # R0901)
282
+ ignored-parents=
283
+
284
+ # Maximum number of arguments for function / method.
285
+ max-args=20
286
+
287
+ # Maximum number of attributes for a class (see R0902).
288
+ max-attributes=20
289
+
290
+ # Maximum number of boolean expressions in an if statement (see R0916).
291
+ max-bool-expr=5
292
+
293
+ # Maximum number of branch for function / method body.
294
+ max-branches=12
295
+
296
+ # Maximum number of locals for function / method body.
297
+ max-locals=32
298
+
299
+ # Maximum number of parents for a class (see R0901).
300
+ max-parents=7
301
+
302
+ # Maximum number of public methods for a class (see R0904).
303
+ max-public-methods=24
304
+
305
+ # Maximum number of return / yield for function / method body.
306
+ max-returns=6
307
+
308
+ # Maximum number of statements in function / method body.
309
+ max-statements=60
310
+
311
+ # Minimum number of public methods for a class (see R0903).
312
+ min-public-methods=2
313
+
314
+
315
+ [EXCEPTIONS]
316
+
317
+ # Exceptions that will emit a warning when caught.
318
+ overgeneral-exceptions=BaseException,
319
+ Exception
320
+
321
+
322
+ [FORMAT]
323
+
324
+ # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
325
+ expected-line-ending-format=
326
+
327
+ # Regexp for a line that is allowed to be longer than the limit.
328
+ ignore-long-lines=^\s*(# )?<?https?://\S+>?$
329
+
330
+ # Number of spaces of indent required inside a hanging or continued line.
331
+ indent-after-paren=4
332
+
333
+ # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
334
+ # tab).
335
+ indent-string=' '
336
+
337
+ # Maximum number of characters on a single line.
338
+ max-line-length=100
339
+
340
+ # Maximum number of lines in a module.
341
+ max-module-lines=1000
342
+
343
+ # Allow the body of a class to be on the same line as the declaration if body
344
+ # contains single statement.
345
+ single-line-class-stmt=no
346
+
347
+ # Allow the body of an if to be on the same line as the test if there is no
348
+ # else.
349
+ single-line-if-stmt=no
350
+
351
+
352
+ [IMPORTS]
353
+
354
+ # List of modules that can be imported at any level, not just the top level
355
+ # one.
356
+ allow-any-import-level=
357
+
358
+ # Allow wildcard imports from modules that define __all__.
359
+ allow-wildcard-with-all=no
360
+
361
+ # Deprecated modules which should not be used, separated by a comma.
362
+ deprecated-modules=
363
+
364
+ # Output a graph (.gv or any supported image format) of external dependencies
365
+ # to the given file (report RP0402 must not be disabled).
366
+ ext-import-graph=
367
+
368
+ # Output a graph (.gv or any supported image format) of all (i.e. internal and
369
+ # external) dependencies to the given file (report RP0402 must not be
370
+ # disabled).
371
+ import-graph=
372
+
373
+ # Output a graph (.gv or any supported image format) of internal dependencies
374
+ # to the given file (report RP0402 must not be disabled).
375
+ int-import-graph=
376
+
377
+ # Force import order to recognize a module as part of the standard
378
+ # compatibility libraries.
379
+ known-standard-library=
380
+
381
+ # Force import order to recognize a module as part of a third party library.
382
+ known-third-party=enchant
383
+
384
+ # Couples of modules and preferred modules, separated by a comma.
385
+ preferred-modules=
386
+
387
+
388
+ [LOGGING]
389
+
390
+ # The type of string formatting that logging methods do. `old` means using %
391
+ # formatting, `new` is for `{}` formatting.
392
+ logging-format-style=old
393
+
394
+ # Logging modules to check that the string format arguments are in logging
395
+ # function parameter format.
396
+ logging-modules=logging
397
+
398
+
399
+ [MESSAGES CONTROL]
400
+
401
+ # Only show warnings with the listed confidence levels. Leave empty to show
402
+ # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
403
+ # UNDEFINED.
404
+ confidence=HIGH,
405
+ CONTROL_FLOW,
406
+ INFERENCE,
407
+ INFERENCE_FAILURE,
408
+ UNDEFINED
409
+
410
+ # Disable the message, report, category or checker with the given id(s). You
411
+ # can either give multiple identifiers separated by comma (,) or put this
412
+ # option multiple times (only on the command line, not in the configuration
413
+ # file where it should appear only once). You can also use "--disable=all" to
414
+ # disable everything first and then re-enable specific checks. For example, if
415
+ # you want to run only the similarities checker, you can use "--disable=all
416
+ # --enable=similarities". If you want to run only the classes checker, but have
417
+ # no Warning level messages displayed, use "--disable=all --enable=classes
418
+ # --disable=W".
419
+ disable=raw-checker-failed,
420
+ bad-inline-option,
421
+ locally-disabled,
422
+ file-ignored,
423
+ suppressed-message,
424
+ useless-suppression,
425
+ deprecated-pragma,
426
+ missing-module-docstring,
427
+ use-symbolic-message-instead,
428
+ invalid-name,
429
+ too-few-public-methods,
430
+ logging-fstring-interpolation,
431
+ global-statement,
432
+ no-member,
433
+ no-value-for-parameter,
434
+ cell-var-from-loop,
435
+ invalid-unary-operand-type,
436
+ unbalanced-tuple-unpacking,
437
+ no-else-return,
438
+ missing-type-doc,
439
+
440
+ # Enable the message, report, category or checker with the given id(s). You can
441
+ # either give multiple identifier separated by comma (,) or put this option
442
+ # multiple time (only on the command line, not in the configuration file where
443
+ # it should appear only once). See also the "--disable" option for examples.
444
+ enable=c-extension-no-member
445
+
446
+
447
+ [METHOD_ARGS]
448
+
449
+ # List of qualified names (i.e., library.method) which require a timeout
450
+ # parameter e.g. 'requests.api.get,requests.api.post'
451
+ timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
452
+
453
+
454
+ [MISCELLANEOUS]
455
+
456
+ # List of note tags to take in consideration, separated by a comma.
457
+ notes=FIXME,
458
+ XXX,
459
+ TODO
460
+
461
+ # Regular expression of note tags to take in consideration.
462
+ notes-rgx=
463
+
464
+
465
+ [REFACTORING]
466
+
467
+ # Maximum number of nested blocks for function / method body
468
+ max-nested-blocks=5
469
+
470
+ # Complete name of functions that never returns. When checking for
471
+ # inconsistent-return-statements if a never returning function is called then
472
+ # it will be considered as an explicit return statement and no message will be
473
+ # printed.
474
+ never-returning-functions=sys.exit,argparse.parse_error
475
+
476
+
477
+ [REPORTS]
478
+
479
+ # Python expression which should return a score less than or equal to 10. You
480
+ # have access to the variables 'fatal', 'error', 'warning', 'refactor',
481
+ # 'convention', and 'info' which contain the number of messages in each
482
+ # category, as well as 'statement' which is the total number of statements
483
+ # analyzed. This score is used by the global evaluation report (RP0004).
484
+ evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
485
+
486
+ # Template used to display messages. This is a python new-style format string
487
+ # used to format the message information. See doc for all details.
488
+ msg-template=
489
+
490
+ # Set the output format. Available formats are text, parseable, colorized, json
491
+ # and msvs (visual studio). You can also give a reporter class, e.g.
492
+ # mypackage.mymodule.MyReporterClass.
493
+ #output-format=
494
+
495
+ # Tells whether to display a full report or only the messages.
496
+ reports=no
497
+
498
+ # Activate the evaluation score.
499
+ score=yes
500
+
501
+
502
+ [SIMILARITIES]
503
+
504
+ # Comments are removed from the similarity computation
505
+ ignore-comments=yes
506
+
507
+ # Docstrings are removed from the similarity computation
508
+ ignore-docstrings=yes
509
+
510
+ # Imports are removed from the similarity computation
511
+ ignore-imports=yes
512
+
513
+ # Signatures are removed from the similarity computation
514
+ ignore-signatures=yes
515
+
516
+ # Minimum lines number of a similarity.
517
+ min-similarity-lines=4
518
+
519
+
520
+ [SPELLING]
521
+
522
+ # Limits count of emitted suggestions for spelling mistakes.
523
+ max-spelling-suggestions=4
524
+
525
+ # Spelling dictionary name. Available dictionaries: none. To make it work,
526
+ # install the 'python-enchant' package.
527
+ spelling-dict=
528
+
529
+ # List of comma separated words that should be considered directives if they
530
+ # appear at the beginning of a comment and should not be checked.
531
+ spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
532
+
533
+ # List of comma separated words that should not be checked.
534
+ spelling-ignore-words=
535
+
536
+ # A path to a file that contains the private dictionary; one word per line.
537
+ spelling-private-dict-file=
538
+
539
+ # Tells whether to store unknown words to the private dictionary (see the
540
+ # --spelling-private-dict-file option) instead of raising a message.
541
+ spelling-store-unknown-words=no
542
+
543
+
544
+ [STRING]
545
+
546
+ # This flag controls whether inconsistent-quotes generates a warning when the
547
+ # character used as a quote delimiter is used inconsistently within a module.
548
+ check-quote-consistency=no
549
+
550
+ # This flag controls whether the implicit-str-concat should generate a warning
551
+ # on implicit string concatenation in sequences defined over several lines.
552
+ check-str-concat-over-line-jumps=no
553
+
554
+
555
+ [TYPECHECK]
556
+
557
+ # List of decorators that produce context managers, such as
558
+ # contextlib.contextmanager. Add to this list to register other decorators that
559
+ # produce valid context managers.
560
+ contextmanager-decorators=contextlib.contextmanager
561
+
562
+ # List of members which are set dynamically and missed by pylint inference
563
+ # system, and so shouldn't trigger E1101 when accessed. Python regular
564
+ # expressions are accepted.
565
+ generated-members=numpy.*, torch.*
566
+
567
+ # Tells whether to warn about missing members when the owner of the attribute
568
+ # is inferred to be None.
569
+ ignore-none=yes
570
+
571
+ # This flag controls whether pylint should warn about no-member and similar
572
+ # checks whenever an opaque object is returned when inferring. The inference
573
+ # can return multiple potential results while evaluating a Python object, but
574
+ # some branches might not be evaluated, which results in partial inference. In
575
+ # that case, it might be useful to still emit no-member and other checks for
576
+ # the rest of the inferred objects.
577
+ ignore-on-opaque-inference=yes
578
+
579
+ # List of symbolic message names to ignore for Mixin members.
580
+ ignored-checks-for-mixins=no-member,
581
+ not-async-context-manager,
582
+ not-context-manager,
583
+ attribute-defined-outside-init
584
+
585
+ # List of class names for which member attributes should not be checked (useful
586
+ # for classes with dynamically set attributes). This supports the use of
587
+ # qualified names.
588
+ ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
589
+
590
+ # Show a hint with possible names when a member name was not found. The aspect
591
+ # of finding the hint is based on edit distance.
592
+ missing-member-hint=yes
593
+
594
+ # The minimum edit distance a name should have in order to be considered a
595
+ # similar match for a missing member name.
596
+ missing-member-hint-distance=1
597
+
598
+ # The total number of similar names that should be taken in consideration when
599
+ # showing a hint for a missing member.
600
+ missing-member-max-choices=1
601
+
602
+ # Regex pattern to define which classes are considered mixins.
603
+ mixin-class-rgx=.*[Mm]ixin
604
+
605
+ # List of decorators that change the signature of a decorated function.
606
+ signature-mutators=
607
+
608
+
609
+ [VARIABLES]
610
+
611
+ # List of additional names supposed to be defined in builtins. Remember that
612
+ # you should avoid defining new builtins when possible.
613
+ additional-builtins=
614
+
615
+ # Tells whether unused global variables should be treated as a violation.
616
+ allow-global-unused-variables=yes
617
+
618
+ # List of names allowed to shadow builtins
619
+ allowed-redefined-builtins=
620
+
621
+ # List of strings which can identify a callback function by name. A callback
622
+ # name must start or end with one of those strings.
623
+ callbacks=cb_,
624
+ _cb
625
+
626
+ # A regular expression matching the name of dummy variables (i.e. expected to
627
+ # not be used).
628
+ dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
629
+
630
+ # Argument names that match this expression will be ignored.
631
+ ignored-argument-names=_.*|^ignored_|^unused_|args|kwargs
632
+
633
+ # Tells whether we should check for unused import in __init__ files.
634
+ init-import=no
635
+
636
+ # List of qualified module names which can have objects that can redefine
637
+ # builtins.
638
+ redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
gafl/build/geometric-algebra-transformer/CHANGELOG.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## [1.2.0] - 2024-02-19
4
+
5
+ ### Added
6
+
7
+ - Expose `join_reference` kwarg in `GATr.forward()`, `AxialGATr.forward()`
8
+ - Add utility function `gatr.utils.compile_linear.compile_equi_linear_submodules()`
9
+
10
+ ### Removed
11
+
12
+ - Remove option to *not* provide a position in `embed_oriented_plane()`, `embed_reflection()`
13
+
14
+ ## [1.1.1] - 2024-01-10
15
+
16
+ _Minor cleanup._
17
+
18
+ ## [1.1.0] - 2024-01-02
19
+
20
+ ### Changed
21
+
22
+ - Change dimension collapse behaviour in `AxialGATr` and `BaselineAxialTransformer`
23
+
24
+ ### Added
25
+
26
+ - Add hooks functionality and `register_hook()` method to `BaseExperiment`
27
+
28
+ ### Fixed
29
+
30
+ - Fix critical bug in `embed_3d_object_two_vec()` that lead to wrong results when any tensor dimension was 3
31
+ - Fix various minor issues in `BaseExperiment`
32
+ - Improve logging in `BaseExperiment`
33
+
34
+ ## [1.0.0] - 2023-10-19
35
+
36
+ _First release._
gafl/build/geometric-algebra-transformer/GATr.egg-info/PKG-INFO ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: GATr
3
+ Version: 1.2.0
4
+ Summary: The Geometric Algebra Transformer, a universal neural network architecture for geometric data
5
+ Home-page: https://github.com/Qualcomm-AI-research/geometric-algebra-transformer
6
+ Author: Johann Brehmer, Pim de Haan, Sönke Behrends, and Taco Cohen
7
+ Author-email: jbrehmer@qti.qualcomm.com
8
+ Maintainer: Johann Brehmer
9
+ Maintainer-email: jbrehmer@qti.qualcomm.com
10
+ License: See notice in license file
11
+ Requires-Python: >=3.8
12
+ License-File: LICENSE
13
+ Requires-Dist: einops
14
+ Requires-Dist: numpy<1.25
15
+ Requires-Dist: opt_einsum @ git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10
16
+ Requires-Dist: torch>=2.0
17
+ Requires-Dist: xformers
18
+ Dynamic: author
19
+ Dynamic: author-email
20
+ Dynamic: home-page
21
+ Dynamic: license
22
+ Dynamic: license-file
23
+ Dynamic: maintainer
24
+ Dynamic: maintainer-email
25
+ Dynamic: requires-dist
26
+ Dynamic: requires-python
27
+ Dynamic: summary
gafl/build/geometric-algebra-transformer/GATr.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ GATr.egg-info/PKG-INFO
6
+ GATr.egg-info/SOURCES.txt
7
+ GATr.egg-info/dependency_links.txt
8
+ GATr.egg-info/requires.txt
9
+ GATr.egg-info/top_level.txt
10
+ gatr/__init__.py
11
+ gatr/baselines/__init__.py
12
+ gatr/baselines/gcan.py
13
+ gatr/baselines/mlp.py
14
+ gatr/baselines/segnn.py
15
+ gatr/baselines/transformer.py
16
+ gatr/experiments/__init__.py
17
+ gatr/experiments/base_experiment.py
18
+ gatr/experiments/base_wrapper.py
19
+ gatr/experiments/arteries/__init__.py
20
+ gatr/experiments/arteries/dataset.py
21
+ gatr/experiments/arteries/experiment.py
22
+ gatr/experiments/arteries/wrappers.py
23
+ gatr/experiments/nbody/__init__.py
24
+ gatr/experiments/nbody/dataset.py
25
+ gatr/experiments/nbody/experiment.py
26
+ gatr/experiments/nbody/simulator.py
27
+ gatr/experiments/nbody/wrappers.py
28
+ gatr/interface/__init__.py
29
+ gatr/interface/object.py
30
+ gatr/interface/plane.py
31
+ gatr/interface/point.py
32
+ gatr/interface/pseudoscalar.py
33
+ gatr/interface/reflection.py
34
+ gatr/interface/rotation.py
35
+ gatr/interface/scalar.py
36
+ gatr/interface/translation.py
37
+ gatr/layers/__init__.py
38
+ gatr/layers/dropout.py
39
+ gatr/layers/gatr_block.py
40
+ gatr/layers/layer_norm.py
41
+ gatr/layers/linear.py
42
+ gatr/layers/attention/__init__.py
43
+ gatr/layers/attention/attention.py
44
+ gatr/layers/attention/config.py
45
+ gatr/layers/attention/positional_encoding.py
46
+ gatr/layers/attention/qkv.py
47
+ gatr/layers/attention/self_attention.py
48
+ gatr/layers/mlp/__init__.py
49
+ gatr/layers/mlp/config.py
50
+ gatr/layers/mlp/geometric_bilinears.py
51
+ gatr/layers/mlp/mlp.py
52
+ gatr/layers/mlp/nonlinearities.py
53
+ gatr/nets/__init__.py
54
+ gatr/nets/axial_gatr.py
55
+ gatr/nets/gatr.py
56
+ gatr/primitives/__init__.py
57
+ gatr/primitives/attention.py
58
+ gatr/primitives/bilinear.py
59
+ gatr/primitives/dropout.py
60
+ gatr/primitives/dual.py
61
+ gatr/primitives/invariants.py
62
+ gatr/primitives/linear.py
63
+ gatr/primitives/nonlinearities.py
64
+ gatr/primitives/normalization.py
65
+ gatr/primitives/data/geometric_product.pt
66
+ gatr/primitives/data/outer_product.pt
67
+ gatr/utils/__init__.py
68
+ gatr/utils/clifford.py
69
+ gatr/utils/compile_linear.py
70
+ gatr/utils/dual_basis.py
71
+ gatr/utils/einsum.py
72
+ gatr/utils/logger.py
73
+ gatr/utils/misc.py
74
+ gatr/utils/mlflow.py
75
+ gatr/utils/plotting.py
76
+ gatr/utils/quaternions.py
77
+ gatr/utils/tensors.py
78
+ scripts/artery_experiment.py
79
+ scripts/generate_nbody_dataset.py
80
+ scripts/nbody_experiment.py
gafl/build/geometric-algebra-transformer/GATr.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
gafl/build/geometric-algebra-transformer/GATr.egg-info/requires.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ einops
2
+ numpy<1.25
3
+ opt_einsum @ git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10
4
+ torch>=2.0
5
+ xformers
gafl/build/geometric-algebra-transformer/GATr.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gatr
gafl/build/geometric-algebra-transformer/LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer:
8
+
9
+ * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
10
+
11
+ * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
12
+
13
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
gafl/build/geometric-algebra-transformer/README.md ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Geometric Algebra Transformers
2
+
3
+ This repository contains the official implementation of the
4
+ [**Geometric Algebra Transformer**](https://arxiv.org/abs/2305.18415) by
5
+ [Johann Brehmer](mailto:jbrehmer@qti.qualcomm.com), Pim de Haan, Sönke Behrends, and Taco Cohen,
6
+ published at NeurIPS 2023.
7
+
8
+ ![GATr = geometric algebra representations + equivariant layers + Transformer architecture](img/gatr.png)
9
+
10
+ ## 1. Abstract
11
+
12
+ Problems involving geometric data arise in physics, chemistry, robotics, computer vision, and many
13
+ other fields. Such data can take numerous forms, such as points, direction vectors, translations, or
14
+ rotations, but to date there is no single architecture that can be applied to such a wide variety of
15
+ geometric types while respecting their symmetries. In this paper we introduce the Geometric Algebra
16
+ Transformer (GATr), a general-purpose architecture for geometric data. GATr represents inputs,
17
+ outputs, and hidden states in the projective geometric (or Clifford) algebra, which offers an
18
+ efficient 16-dimensional vector-space representation of common geometric objects as well as
19
+ operators acting on them. GATr is equivariant with respect to E(3), the symmetry group of 3D
20
+ Euclidean space. As a Transformer, GATr is versatile, efficient, and scalable. We demonstrate GATr
21
+ in problems from n-body modeling to wall-shear-stress estimation on large arterial meshes to robotic
22
+ motion planning. GATr consistently outperforms both non-geometric and equivariant baselines in terms
23
+ of error, data efficiency, and scalability.
24
+
25
+ ## 2. Getting started
26
+
27
+ Clone the repository.
28
+
29
+ ```bash
30
+ git clone https://github.com/Qualcomm-AI-research/geometric-algebra-transformer
31
+ ```
32
+
33
+ Build the Docker image from inside the checked-out repository. On Linux, this can be done using
34
+
35
+ ```bash
36
+ cd geometric-algebra-transformer
37
+ docker build -f docker/Dockerfile --tag gatr:latest .
38
+ ```
39
+
40
+ The commands for Windows are similar.
41
+
42
+ Once the image has built successfully, we can run a container that is based on it.
43
+
44
+ On Linux, the command that does this and also
45
+
46
+ - mounts the current working directory into the container
47
+ - changes to the current working directory
48
+ - exposes all of the host's GPUs in the container
49
+
50
+ is
51
+
52
+ ```bash
53
+ docker run --rm -it -v $PWD:$PWD -w $PWD --gpus=all gatr:latest /bin/bash
54
+ ```
55
+
56
+ ## 3. Running experiments
57
+
58
+ In this repository, we include two experiments: one on a synthetic n-body modeling problem and one
59
+ on predicting the wall shear stress on artery walls.
60
+
61
+ Running experiments will require the specification of directories for datasets, checkpoints, and
62
+ logs. We will define a common base directory (feel free to adapt):
63
+
64
+ ```bash
65
+ BASEDIR=/tmp/gatr-experiments
66
+ ```
67
+
68
+ ### n-body modeling
69
+
70
+ First, we need to generate training and evaluation datasets:
71
+
72
+ ```bash
73
+ python scripts/generate_nbody_dataset.py base_dir="${BASEDIR}" seed=42
74
+ ```
75
+
76
+ Let's train a GATr model, using just 1000 (or 1%) training trajectories and training for 5000 steps:
77
+
78
+ ```bash
79
+ python scripts/nbody_experiment.py base_dir="${BASEDIR}" seed=42 model=gatr_nbody data.subsample=0.01 training.steps=5000 run_name=gatr
80
+ ```
81
+
82
+ At the end of the training, evaluation metrics are printed to stdout
83
+ and written to `$BASEDIR/experiments/nbody/gatr/metrics`. Training and evaluation are also
84
+ tracked with MLflow to an SQLite database at `$BASEDIR/tracking/mlflow.db`.
85
+ MLFlow is configured in the `mlflow` section of `config/nbody.yaml`.
86
+
87
+ We can repeat the same for different baselines, for instance:
88
+
89
+ ```bash
90
+ for METHOD in mlp transformer gcagnn se3transformer segnn
91
+ do
92
+ python scripts/nbody_experiment.py base_dir="${BASEDIR}" seed=42 model=${METHOD}_nbody data.subsample=0.01 training.steps=5000 run_name=$METHOD
93
+ done
94
+ ```
95
+
96
+ On the `eval` set (without domain shift), you should get results like these:
97
+
98
+ ```text
99
+ Method | MSE
100
+ ----------------+--------
101
+ GATr | 0.0005
102
+ ----------------+--------
103
+ MLP | 0.0776
104
+ Transformer | 0.0050
105
+ GCA-GNN | 0.0526
106
+ SE3-Transformer | 0.0025
107
+ SEGNN | 0.0006
108
+ ```
109
+
110
+ Note that the code is
111
+ [not fully deterministic](https://pytorch.org/docs/stable/notes/randomness.html), so you will not
112
+ get these exact numbers. (After averaging over multiple seeds, such fluctuations should be
113
+ negligible).
114
+
115
+ You can also vary the number of training samples seen (`data.subsample`), the number of optimizer
116
+ steps (`training.steps`), the random seed (`seed`), and many other settings. Have a look at
117
+ [the n-body config](config/nbody.yaml) and [the GATr model config](config/model/gatr_nbody.yaml).
118
+
119
+ If you train for long enough and average results from multiple random seeds, you should get numbers
120
+ that are comparable to Fig. 2 in our paper. However, do not expect exact reproducibility: the paper
121
+ experiments were performed with an earlier version of GATr than the one published in this
122
+ repository. In addition, there is stochasticity both in the dataset generation and in the
123
+ initialization and training of the networks.
124
+
125
+ ### Arterial wall-shear-stress estimation
126
+
127
+ The arterial wall-shear-stress experiment uses a dataset created by
128
+ [Julian Suk et al](https://arxiv.org/abs/2212.05023).
129
+
130
+ First, you need to download that dataset following
131
+ [the instructions in their repo](https://github.com/sukjulian/coronary-mesh-convolution#data).
132
+ We only need the single (not bifurcating) dataset. Store this dataset at some location
133
+ `$ARTERYDIR/raw/database.hdf5` and set the environment variable `$ARTERYDIR` correspondingly
134
+ (as we will use it in the commands below).
135
+
136
+ To train a GATr model on a non-canonicalized version of this dataset for 20k steps, run:
137
+
138
+ ```shell
139
+ python scripts/artery_experiment.py base_dir="${BASEDIR}" data.data_dir="${ARTERYDIR}" seed=42 training.lr_decay=0.1 training.steps=50000 model=gatr_arteries run_name=gatr
140
+ ```
141
+
142
+ To train a Transformer baseline, run:
143
+
144
+ ```shell
145
+ python scripts/artery_experiment.py base_dir="${BASEDIR}" data.data_dir="${ARTERYDIR}" seed=42 training.lr_decay=0.1 training.steps=50000 model=transformer_arteries run_name=transformer_arteries
146
+ ```
147
+
148
+ Eventually you should find results like these:
149
+
150
+ ```text
151
+ Method | Approximation error
152
+ -------------+---------------------
153
+ GATr | 0.089
154
+ Transformer | 0.105
155
+ ```
156
+
157
+ If you run for long enough, you should get results comparable to Fig. 3 and Tbl. 2 in our paper.
158
+ Similar to the nbody experiment, results are also tracked with MLFlow.
159
+ Again, there is no guarantee for exact reproducibility due to code changes and stochasticity.
160
+
161
+ ## 4. Using GATr
162
+
163
+ To use GATr on your own problem, you will at least need two components from this repository:
164
+ GATr networks, which act on multivector data, and interface functions that embed various geometric
165
+ objects into this multivector representations.
166
+
167
+ Here is an example code snippet that illustrates the recipe:
168
+
169
+ ```python
170
+ from gatr import GATr, SelfAttentionConfig, MLPConfig
171
+ from gatr.interface import embed_point, extract_scalar
172
+ import torch
173
+
174
+
175
+ class ExampleWrapper(torch.nn.Module):
176
+ """Example wrapper around a GATr model.
177
+
178
+ Expects input data that consists of a point cloud: one 3D point for each item in the data.
179
+ Returns outputs that consists of one scalar number for the whole dataset.
180
+
181
+ Parameters
182
+ ----------
183
+ blocks : int
184
+ Number of transformer blocks
185
+ hidden_mv_channels : int
186
+ Number of hidden multivector channels
187
+ hidden_s_channels : int
188
+ Number of hidden scalar channels
189
+ """
190
+
191
+ def __init__(self, blocks=20, hidden_mv_channels=16, hidden_s_channels=32):
192
+ super().__init__()
193
+ self.gatr = GATr(
194
+ in_mv_channels=1,
195
+ out_mv_channels=1,
196
+ hidden_mv_channels=hidden_mv_channels,
197
+ in_s_channels=None,
198
+ out_s_channels=None,
199
+ hidden_s_channels=hidden_s_channels,
200
+ num_blocks=blocks,
201
+ attention=SelfAttentionConfig(), # Use default parameters for attention
202
+ mlp=MLPConfig(), # Use default parameters for MLP
203
+ )
204
+
205
+ def forward(self, inputs):
206
+ """Forward pass.
207
+
208
+ Parameters
209
+ ----------
210
+ inputs : torch.Tensor with shape (*batch_dimensions, num_points, 3)
211
+ Point cloud input data
212
+
213
+ Returns
214
+ -------
215
+ outputs : torch.Tensor with shape (*batch_dimensions, 1)
216
+ Model prediction: a single scalar for the whole point cloud.
217
+ """
218
+
219
+ # Embed point cloud in PGA
220
+ embedded_inputs = embed_point(inputs).unsqueeze(-2) # (..., num_points, 1, 16)
221
+
222
+ # Pass data through GATr
223
+ embedded_outputs, _ = self.gatr(embedded_inputs, scalars=None) # (..., num_points, 1, 16)
224
+
225
+ # Extract scalar and aggregate outputs from point cloud
226
+ nodewise_outputs = extract_scalar(embedded_outputs) # (..., num_points, 1, 1)
227
+ outputs = torch.mean(nodewise_outputs, dim=(-3, -2)) # (..., 1)
228
+
229
+ return outputs
230
+ ```
231
+
232
+ In the following, we will go into more detail on the conventions used in this code base and the
233
+ structure of the repository.
234
+
235
+ ### Design choices
236
+
237
+ **Representations**: GATr operates with two kind of representations: geometric algebra multivectors
238
+ and auxiliary scalar representations. Both are simply represented as `torch.Tensor` instances.
239
+
240
+ The multivectors are based on the projective geometric algebra G(3, 0, 1). They are tensors of the
241
+ shape `(..., 16)`, for instance `(batchsize, items, channels, 16)`. The sixteen multivector
242
+ components are sorted as in the
243
+ [`clifford` library](https://clifford.readthedocs.io/en/latest/), as follows:
244
+ `[x_scalars, x_0, x_1, x_2, x_3, x_01, x_02, x_03, x_12, x_13, x_23, x_012, x_013, x_023, x_123,
245
+ x_0123]`.
246
+
247
+ Scalar representations have free shapes, but should match the multivector representations they
248
+ accompany in batchsize and number of items. The number of channels may be different.
249
+
250
+ **Interface to the real world**: To map the multivector representations to physical objects, we
251
+ use the plane-based convention presented in
252
+ [Roelfs and De Keninck, "Graded symmetry groups: Plane and simple"](https://arxiv.org/abs/2107.03771).
253
+ 3D points are thus represented as trivectors, planes as vectors, and so on. We provide these
254
+ these interface functions in the `gatr.interface` submodule.
255
+
256
+ **Functions**: We distinguish between primitives (functions) and layers (often stateful
257
+ `torch.nn.Module` instances). Almost all primitives and layers are Pin(3, 0, 1)-equivariant,
258
+ see docstrings for exceptions.
259
+
260
+ ### Repository structure
261
+
262
+ ```text
263
+ geometric-algebra-transformer
264
+ |
265
+ └───config: configuration YAML files for the experiments
266
+ | └───model: model configurations
267
+ | | arteries.yaml: default configuration for the artery experiment
268
+ | | hydra.yaml: hydra configuration (imported by the experiment configs)
269
+ | | nbody.yaml: default configuration for the n-body experiment
270
+ |
271
+ └───docker: Docker environment
272
+ | └───ext_packages: patches for external dependencies
273
+ | | Dockerfile: Docker container specification
274
+ | | requirements.txt: external dependencies installed in Dockerfile
275
+ |
276
+ └───gatr: core library
277
+ | └───baselines: baseline layers and architectures
278
+ | | | gcan.py: GCA-MLP and GCA-GNN baselines
279
+ | | | mlp.py: MLP baseline
280
+ | | | segnn.py: SEGNN baseline
281
+ | | | transformer.py: Transformer baseline
282
+ | |
283
+ | └───experiments: experiment managers
284
+ | | └───arteries: experiment manager, wrappers, etc for the artery experiment
285
+ | | └───nbody: experiment manager, wrappers, etc for the n-body experiment
286
+ | | | base_experiment.py: base class for experiment managers
287
+ | | | base_wrapper.py: base class for experiment-specific GATr wrappers
288
+ | |
289
+ | └───interface: embedding of geometric quantities into projective geometric algebra
290
+ | | | object.py: 3D objects consisting of positions and orientations
291
+ | | | plane.py: planes
292
+ | | | point.py: points
293
+ | | | pseudoscalar.py: pseudoscalars
294
+ | | | reflection.py: planar reflections
295
+ | | | rotation.py: rotations
296
+ | | | scalar.py: scalars
297
+ | | | translation.py: translations
298
+ | |
299
+ | └───layers: network layers
300
+ | | └───attention: self-attention layer, its components, and the corresponding configuration
301
+ | | └───mlp: geometric MLP, its components, and the corresponding configuration
302
+ | | | dropout.py: multivector dropout
303
+ | | | gatr_block.py: GATr transformer block, the main layer that GATr networks consist of
304
+ | | | layer_norm.py: geometric LayerNorm
305
+ | | | linear.py: equivariant linear layer between multivectors
306
+ | |
307
+ | └───nets: complete network architectures
308
+ | | | axial_gatr.py: axial-attention version of GATr for two token dimensions
309
+ | | | gatr.py: GATr architecture for a single token dimension
310
+ | |
311
+ | └───primitives: core functional building blocks of GATr
312
+ | | └───data: pre-computed basis stored in `.pt` files
313
+ | | | attention.py: geometric attention mechanism
314
+ | | | bilinear.py: bilinear equivariant functions like the geometric product
315
+ | | | dropout.py: geometric dropout
316
+ | | | dual.py: dual-related functions like the equivariant join
317
+ | | | invariants.py: invariant functions of multivectors like the norm
318
+ | | | linear.py: equivariant linear maps between multivectors
319
+ | | | nonlinearities.py: gated nonlinearities
320
+ | | | normalization.py: geometric normalization functions
321
+ | |
322
+ | └───utils: utility functions
323
+ | | clifford.py: non-differentiable GA functions based on the clifford library
324
+ | | dual_basis.py: helper functions to construct the equivariant join efficiently
325
+ | | einsum.py: optimized einsum function
326
+ | | logger.py: logger
327
+ | | misc.py: various utility functions
328
+ | | mlflow.py: logging with MLflow
329
+ | | plotting.py: plotting defaults
330
+ | | quaternions.py: quaternion operations
331
+ | | tensors.py: various tensor operations
332
+ |
333
+ └───scripts: entrypoints to run experiments
334
+ | | artery_experiment.py: artery experiment script
335
+ | | generate_nbody_dataset.py: data generation script for the n-body experiment
336
+ | | nbody_experiment.py: n-body experiment script
337
+ │
338
+ └───tests: unit tests (e.g. for self-consistency and Pin equivariance)
339
+ | └───gatr
340
+ | | └───baselines: unit tests for gatr.baselines
341
+ | | └───interface: unit tests for gatr.interface
342
+ | | └───layers: unit tests for gatr.layers
343
+ | | └───nets: unit tests for gatr.nets
344
+ | | └───primitives: unit tests for gatr.primitives
345
+ | | └───utils: unit tests for gatr.utils
346
+ | |
347
+ | └───helpers: utility functions for unit tests
348
+ | | constants.py: test settings (like tolerances)
349
+ | | equivariance.py: helper functions to test Pin equivariance
350
+ | | geometric_algebra.py: helper functions to test GA functionality
351
+ │
352
+ └───tests_regression: regression tests (training a GATr to predict the distance between points)
353
+ │
354
+ | .coveragerc: coverage configuration
355
+ | .dockerignore: Docker configuration
356
+ | .gitignore: git configuration
357
+ │ .pylintrc: pylint configuration
358
+ │ LICENSE: license under which this code may be used
359
+ │ pyproject.toml: project settings
360
+ │ README.md: this README file
361
+ │ setup.py: installation script
362
+ ```
363
+
364
+ ## 5. Other geometric algebras
365
+
366
+ The GATr paper and this repository use the projective geometric algebra. In the work
367
+ [Euclidean, Projective, Conformal: Choosing a Geometric Algebra for Equivariant Transformers](https://arxiv.org/abs/2311.04744),
368
+ we explored using the Euclidean and conformal algebras instead. We found a nuanced trade-off
369
+ between the different algebras for their use in GATr. At the moment, the code for the different
370
+ algebras has not been released.
371
+
372
+ ## 6. Citation
373
+
374
+ If you find our code useful, please cite:
375
+
376
+ ```text
377
+ @inproceedings{brehmer2023geometric,
378
+ title = {Geometric Algebra Transformer},
379
+ author = {Brehmer, Johann and de Haan, Pim and Behrends, S{\"o}nke and Cohen, Taco},
380
+ booktitle = {Advances in Neural Information Processing Systems},
381
+ year = {2023},
382
+ volume = {37},
383
+ eprint = {2305.18415},
384
+ url = {https://arxiv.org/abs/2305.18415},
385
+ }
386
+
387
+ @inproceedings{dehaan2023euclidean,
388
+ title={Euclidean, Projective, Conformal: Choosing a Geometric Algebra for Equivariant Transformers},
389
+ author={Pim de Haan and Taco Cohen and Johann Brehmer},
390
+ booktitle = {Proceedings of The 27th International Conference on Artificial Intelligence and Statistics},
391
+ year={2024},
392
+ url = {https://arxiv.org/abs/2311.04744},
393
+ }
394
+ ```
gafl/build/geometric-algebra-transformer/build/lib/gatr/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .layers.attention.config import SelfAttentionConfig
4
+ from .layers.mlp.config import MLPConfig
5
+ from .nets.axial_gatr import AxialGATr
6
+ from .nets.gatr import GATr
7
+
8
+ __version__ = "1.2.0"
gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .mlp import MLP
4
+ from .transformer import BaselineAxialTransformer, BaselineTransformer
gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/gcan.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+
4
+ """Adapted from code by David Ruhe.
5
+
6
+ MIT License
7
+
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ """
28
+
29
+ import numpy as np
30
+ import torch
31
+ from cliffordlayers.cliffordalgebra import CliffordAlgebra
32
+ from cliffordlayers.nn.modules.gcan import MultiVectorAct, PGAConjugateLinear
33
+ from torch import nn
34
+ from torch_geometric.nn import MessagePassing
35
+
36
+
37
+ class GCAMLP(nn.Module):
38
+ """GCA-MLP model.
39
+
40
+ As described in D. Ruhe et al, "Geometric Clifford Algebra Networks".
41
+ Based on layers from the official
42
+ [cliffordlayers code](https://github.com/microsoft/cliffordlayers/tree/main).
43
+
44
+ This network uses the same projective geometric algebra representations as GATr, but is not
45
+ E(3)-equivariant.
46
+
47
+ References
48
+ ----------
49
+ D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594
50
+
51
+ Parameters
52
+ ----------
53
+ in_shape : tuple of int
54
+ Shape expected of input tensors, excluding the 16 components of the multivectors.
55
+ out_shape : tuple of int
56
+ Shape expected for output tensors, excluding the 16 components of the multivectors.
57
+ hidden_channels : int
58
+ Number of hidden channels.
59
+ hidden_layers : int
60
+ Number of hidden layers.
61
+ act_agg : {"linear", "sum", "mean"}
62
+ Aggregation function.
63
+ flatten : bool
64
+ If True, the network flattens the input along all dimensions except the first (batch)
65
+ and last (multivector component) dimension. Otherwise, all dimensions except for the last
66
+ two are treated as batch dimensions.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ in_shape,
72
+ out_shape,
73
+ hidden_channels,
74
+ hidden_layers,
75
+ act_agg="linear",
76
+ flatten=True,
77
+ **kwargs,
78
+ ):
79
+ super().__init__()
80
+
81
+ if not hidden_layers > 0:
82
+ raise NotImplementedError("Only supports > 0 hidden layers")
83
+
84
+ in_channels = np.product(in_shape) if flatten else in_shape[-1]
85
+ out_channels = np.product(out_shape) if flatten else out_shape[-1]
86
+ self.flatten = flatten
87
+ self.in_shape = in_shape
88
+ self.out_shape = out_shape
89
+
90
+ self.pga = CliffordAlgebra((0, 1, 1, 1))
91
+ self.model = self._make_net(
92
+ in_channels, out_channels, hidden_channels, hidden_layers, act_agg
93
+ )
94
+
95
+ def _make_net(self, in_channels, out_channels, hidden_channels, hidden_layers, act_agg):
96
+ """PGA-MLP code as sent by David Ruhe."""
97
+
98
+ all_blades = list(range(16))
99
+ action_blades = (0, 5, 6, 7, 8, 9, 10, 15) # From David; using all blades results in NaNs
100
+
101
+ linear_in = PGAConjugateLinear(
102
+ in_channels,
103
+ hidden_channels,
104
+ self.pga,
105
+ input_blades=all_blades,
106
+ action_blades=action_blades,
107
+ )
108
+ linear_out = nn.Sequential(
109
+ MultiVectorAct(
110
+ hidden_channels,
111
+ self.pga,
112
+ input_blades=all_blades,
113
+ agg=act_agg,
114
+ ),
115
+ PGAConjugateLinear(
116
+ hidden_channels,
117
+ out_channels,
118
+ self.pga,
119
+ input_blades=all_blades,
120
+ action_blades=action_blades,
121
+ ),
122
+ )
123
+ mlp = [
124
+ nn.Sequential(
125
+ MultiVectorAct(
126
+ hidden_channels,
127
+ self.pga,
128
+ input_blades=all_blades,
129
+ agg=act_agg,
130
+ ),
131
+ PGAConjugateLinear(
132
+ hidden_channels,
133
+ hidden_channels,
134
+ self.pga,
135
+ input_blades=all_blades,
136
+ action_blades=action_blades,
137
+ ),
138
+ )
139
+ for _ in range(hidden_layers - 1)
140
+ ]
141
+ return nn.Sequential(linear_in, *mlp, linear_out)
142
+
143
+ def forward(self, inputs: torch.Tensor):
144
+ """Forward pass.
145
+
146
+ Parameters
147
+ ----------
148
+ inputs : torch.Tensor with shape (..., 16)
149
+ Input multivectors.
150
+
151
+ Returns
152
+ -------
153
+ outputs : torch.Tensor with shape (..., 16)
154
+ Output multivectors.
155
+ """
156
+ input_shape = inputs.shape
157
+ if self.flatten:
158
+ # Flatten all non-batch dimensions
159
+ inputs = inputs.reshape(input_shape[0], -1, 16)
160
+ outputs = self.model(inputs)
161
+ if self.flatten:
162
+ outputs = outputs.reshape(input_shape[0], *self.out_shape, 16)
163
+ return outputs
164
+
165
+
166
+ class GCAGNNLayer(MessagePassing): # pylint: disable=abstract-method
167
+ """GCA-GNN layer as described in D. Ruhe et al.
168
+
169
+ This was described in "Geometric Clifford Algebra Networks" by D. Ruhe et. al,
170
+ and in private communication from D. Ruhe.
171
+ Uses the GCAN layers in the official cliffordlayers library, pieces them together based on the
172
+ information in the paper. Follows the PyG message-passing schema.
173
+
174
+ References
175
+ ----------
176
+ D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594
177
+
178
+ Parameters
179
+ ----------
180
+ in_channels : int
181
+ Number of input channels.
182
+ out_channels : int
183
+ Number of output channels.
184
+ message_channels : int
185
+ Number of channels in the messages.
186
+ mlp_hidden_channels : int
187
+ Number of hidden channels in the MLPs.
188
+ mlp_hidden_layers : int
189
+ Number of hidden layers in the MLPs.
190
+ """
191
+
192
+ def __init__(
193
+ self,
194
+ in_channels,
195
+ out_channels,
196
+ message_channels,
197
+ mlp_hidden_channels,
198
+ mlp_hidden_layers,
199
+ ):
200
+ super().__init__(aggr="add", flow="source_to_target", node_dim=-3)
201
+
202
+ # GCA-MLPs for input, output, message, and update functions
203
+ shared_kwargs = dict(
204
+ hidden_channels=mlp_hidden_channels, hidden_layers=mlp_hidden_layers, flatten=False
205
+ )
206
+ self.message_mlp = GCAMLP((2 * in_channels,), (message_channels,), **shared_kwargs)
207
+ self.update_mlp = GCAMLP(
208
+ (in_channels + message_channels,), (out_channels,), **shared_kwargs
209
+ )
210
+
211
+ def forward(self, x, edge_index): # pylint: disable=arguments-differ
212
+ """Forward pass."""
213
+ return self.propagate(edge_index, x=x)
214
+
215
+ def message(self, x_i, x_j): # pylint: disable=arguments-differ
216
+ """Constructs message."""
217
+ features = torch.cat([x_i, x_j], dim=1) # shape (edges, 2*node_channels, 16)
218
+ message = self.message_mlp(features) # shape (edges, message_channels, 16)
219
+ return message
220
+
221
+ def update(self, aggr_out, x): # pylint: disable=arguments-differ
222
+ """Updates node states with aggregated messages."""
223
+
224
+ features = torch.cat(
225
+ [x, aggr_out], dim=1
226
+ ) # shape (nodes, node_channels + message_channels, 16)
227
+ x = self.update_mlp(features) # shape (nodes, node_channels, 16)
228
+ return x
229
+
230
+
231
+ class GCAGNN(nn.Module):
232
+ """GCA-GNN model as described in D. Ruhe et al.
233
+
234
+ The model was described in "Geometric Clifford Algebra Networks" by D.Ruhe et al.,
235
+ and in private communication from D. Ruhe.
236
+
237
+ Combines multiple GCAGNNLayers.
238
+
239
+ This network uses the same projective geometric algebra representations as GATr, but is not
240
+ E(3)-equivariant.
241
+
242
+ References
243
+ ----------
244
+ D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594
245
+
246
+ Parameters
247
+ ----------
248
+ in_channels : int
249
+ Number of input channels.
250
+ out_channels : int
251
+ Number of output channels.
252
+ node_channels : int
253
+ Number of channels in the hidden representation for each node.
254
+ message_channels : int
255
+ Number of channels in the messages.
256
+ mlp_hidden_channels : int
257
+ Number of hidden channels in the MLPs.
258
+ mlp_hidden_layers : int
259
+ Number of hidden layers in the MLPs.
260
+ message_passing_steps : int
261
+ Number of message-passing steps / GCAGNNLayer blocks.
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ in_channels,
267
+ out_channels,
268
+ node_channels,
269
+ message_channels,
270
+ mlp_hidden_channels,
271
+ mlp_hidden_layers,
272
+ message_passing_steps,
273
+ **kwargs,
274
+ ):
275
+ super().__init__()
276
+
277
+ # Construct layers
278
+ self.layers = nn.ModuleList([])
279
+ shared_kwargs = dict(
280
+ mlp_hidden_channels=mlp_hidden_channels,
281
+ mlp_hidden_layers=mlp_hidden_layers,
282
+ message_channels=message_channels,
283
+ )
284
+
285
+ # Initial step: in_channels to node_channels
286
+ self.layers.append(GCAGNNLayer(in_channels, node_channels, **shared_kwargs))
287
+
288
+ # Intermediate steps / layers
289
+ for _ in range(message_passing_steps - 2):
290
+ self.layers.append(GCAGNNLayer(node_channels, node_channels, **shared_kwargs))
291
+
292
+ # Final step: node_channels to out_channels
293
+ self.layers.append(GCAGNNLayer(node_channels, out_channels, **shared_kwargs))
294
+
295
+ def forward(self, x, edge_index):
296
+ """Forward pass."""
297
+ for layer in self.layers:
298
+ x = layer(x, edge_index=edge_index)
299
+ return x
gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/mlp.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from typing import List
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+
9
+
10
+ class MLP(nn.Module):
11
+ """A simple baseline MLP.
12
+
13
+ Flattens all dimensions except batch and uses GELU nonlinearities.
14
+ """
15
+
16
+ def __init__(self, in_shape, out_shape, hidden_channels, hidden_layers):
17
+ super().__init__()
18
+
19
+ if not hidden_layers > 0:
20
+ raise NotImplementedError("Only supports > 0 hidden layers")
21
+
22
+ self.in_shape = in_shape
23
+ self.out_shape = out_shape
24
+
25
+ layers: List[nn.Module] = [nn.Linear(np.product(in_shape), hidden_channels)]
26
+ for _ in range(hidden_layers - 1):
27
+ layers.append(nn.GELU())
28
+ layers.append(nn.Linear(hidden_channels, hidden_channels))
29
+
30
+ layers.append(nn.GELU())
31
+ layers.append(nn.Linear(hidden_channels, np.product(self.out_shape)))
32
+ self.mlp = nn.Sequential(*layers)
33
+
34
+ def forward(self, inputs: torch.Tensor):
35
+ """Forward pass of baseline MLP."""
36
+ batchsize = inputs.shape[0]
37
+ inputs = inputs.reshape(batchsize, -1)
38
+ outputs = self.mlp(inputs)
39
+ outputs = outputs.reshape(batchsize, *self.out_shape)
40
+ return outputs
gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/segnn.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+
4
+ """Adapted from the below.
5
+
6
+ https://github.com/RobDHess/Steerable-E3-GNN/blob/1b95898f6f18204b510ae127d7f38cd29f610f4d/nbody/train_nbody.py
7
+ by Johannes Brandstetter, Rob Hesselink, Erik Bekkers at
8
+ https://github.com/RobDHess/Steerable-E3-GNN
9
+
10
+ MIT License
11
+
12
+ Copyright (c) 2021 Johannes Brandstetter, Rob Hesselink, Erik Bekkers
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ """
32
+
33
+ from e3nn.o3 import Irreps
34
+ from segnn.balanced_irreps import BalancedIrreps, WeightBalancedIrreps
35
+ from segnn.segnn.segnn import SEGNN
36
+ from torch import nn
37
+
38
+
39
+ def _make_segnn_irreps(vec_channels, scalar_channels):
40
+ """Creates an Irreps object for SEGNNModel given a number of O(3) vectors and scalars."""
41
+ assert vec_channels > 0 or scalar_channels > 0
42
+ irreps = []
43
+ if vec_channels > 0:
44
+ irreps.append(f"{vec_channels}x1o")
45
+ if scalar_channels > 0:
46
+ irreps.append(f"{scalar_channels}x0e")
47
+ return Irreps(" + ".join(irreps))
48
+
49
+
50
+ class SEGNNModel(nn.Module):
51
+ """SEGNN baseline.
52
+
53
+ We restrict ourselves to vector and scalar inputs, as those were sufficient for our experiments.
54
+
55
+ References
56
+ ----------
57
+ J. Brandstetter et al, "Geometric and Physical Quantities Improve E(3) Equivariant Message
58
+ Passing", ICLR 2022
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ input_vec_channels=2,
64
+ input_s_channels=1,
65
+ output_vec_channels=1,
66
+ output_s_channels=0,
67
+ additional_message_s_channels=2,
68
+ hidden_features=128,
69
+ lmax_h=2,
70
+ lmax_attr=3,
71
+ subspace_type="weightbalanced",
72
+ layers=7,
73
+ norm="instance",
74
+ pool="avg",
75
+ task="node",
76
+ **kwargs,
77
+ ):
78
+ super().__init__()
79
+
80
+ input_irreps = _make_segnn_irreps(input_vec_channels, input_s_channels)
81
+ output_irreps = _make_segnn_irreps(output_vec_channels, output_s_channels)
82
+ edge_attr_irreps = Irreps.spherical_harmonics(lmax_attr)
83
+ node_attr_irreps = Irreps.spherical_harmonics(lmax_attr)
84
+ additional_message_irreps = _make_segnn_irreps(0, additional_message_s_channels)
85
+
86
+ if subspace_type == "weightbalanced":
87
+ hidden_irreps = WeightBalancedIrreps(
88
+ _make_segnn_irreps(0, hidden_features), node_attr_irreps, sh=True, lmax=lmax_h
89
+ )
90
+ elif subspace_type == "balanced":
91
+ hidden_irreps = BalancedIrreps(lmax_h, hidden_features, True)
92
+ else:
93
+ raise ValueError(f"Unknown subspace type {subspace_type}")
94
+
95
+ self.model = SEGNN(
96
+ input_irreps,
97
+ hidden_irreps,
98
+ output_irreps,
99
+ edge_attr_irreps,
100
+ node_attr_irreps,
101
+ num_layers=layers,
102
+ norm=norm,
103
+ pool=pool,
104
+ task=task,
105
+ additional_message_irreps=additional_message_irreps,
106
+ )
107
+
108
+ def forward(self, *inputs, **kwargs):
109
+ """Forward pass."""
110
+ return self.model(*inputs, **kwargs)
gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/transformer.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ """Baseline transformer."""
4
+
5
+ from functools import partial
6
+ from typing import Optional, Tuple
7
+
8
+ import torch
9
+ from einops import rearrange
10
+ from torch import nn
11
+ from torch.utils.checkpoint import checkpoint
12
+
13
+ from gatr.layers import ApplyRotaryPositionalEncoding
14
+ from gatr.primitives.attention import scaled_dot_product_attention
15
+ from gatr.utils.tensors import to_nd
16
+
17
+ # Default rearrange patterns for odd blocks
18
+ _REARRANGE_PATTERN = "... i j c -> ... j i c"
19
+
20
+
21
+ class BaselineLayerNorm(nn.Module):
22
+ """Baseline layer norm over all dimensions except the first."""
23
+
24
+ @staticmethod
25
+ def forward(inputs: torch.Tensor) -> torch.Tensor:
26
+ """Forward pass.
27
+
28
+ Parameters
29
+ ----------
30
+ inputs : Tensor
31
+ Input data
32
+
33
+ Returns
34
+ -------
35
+ outputs : Tensor
36
+ Normalized inputs.
37
+ """
38
+ return torch.nn.functional.layer_norm(inputs, normalized_shape=inputs.shape[1:])
39
+
40
+
41
+ class MultiHeadQKVLinear(nn.Module):
42
+ """Compute queries, keys, and values via multi-head attention.
43
+
44
+ Parameters
45
+ ----------
46
+ in_channels : int
47
+ Number of input channels.
48
+ hidden_channels : int
49
+ Number of hidden channels = size of query, key, and value.
50
+ num_heads : int
51
+ Number of attention heads.
52
+ """
53
+
54
+ def __init__(self, in_channels, hidden_channels, num_heads):
55
+ super().__init__()
56
+ self.num_heads = num_heads
57
+ self.linear = nn.Linear(in_channels, 3 * hidden_channels * num_heads)
58
+
59
+ def forward(self, inputs):
60
+ """Forward pass.
61
+
62
+ Returns
63
+ -------
64
+ q : Tensor
65
+ Queries
66
+ k : Tensor
67
+ Keys
68
+ v : Tensor
69
+ Values
70
+ """
71
+ qkv = self.linear(inputs) # (..., num_items, 3 * hidden_channels * num_heads)
72
+ q, k, v = rearrange(
73
+ qkv,
74
+ "... items (qkv hidden_channels num_heads) -> qkv ... num_heads items hidden_channels",
75
+ num_heads=self.num_heads,
76
+ qkv=3,
77
+ )
78
+ return q, k, v
79
+
80
+
81
+ class MultiQueryQKVLinear(nn.Module):
82
+ """Compute queries, keys, and values via multi-query attention.
83
+
84
+ Parameters
85
+ ----------
86
+ in_channels : int
87
+ Number of input channels.
88
+ hidden_channels : int
89
+ Number of hidden channels = size of query, key, and value.
90
+ num_heads : int
91
+ Number of attention heads.
92
+ """
93
+
94
+ def __init__(self, in_channels, hidden_channels, num_heads):
95
+ super().__init__()
96
+ self.num_heads = num_heads
97
+ self.q_linear = nn.Linear(in_channels, hidden_channels * num_heads)
98
+ self.k_linear = nn.Linear(in_channels, hidden_channels)
99
+ self.v_linear = nn.Linear(in_channels, hidden_channels)
100
+
101
+ def forward(self, inputs):
102
+ """Forward pass.
103
+
104
+ Parameters
105
+ ----------
106
+ inputs : Tensor
107
+ Input data
108
+
109
+ Returns
110
+ -------
111
+ q : Tensor
112
+ Queries
113
+ k : Tensor
114
+ Keys
115
+ v : Tensor
116
+ Values
117
+ """
118
+ q = rearrange(
119
+ self.q_linear(inputs),
120
+ "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels",
121
+ num_heads=self.num_heads,
122
+ )
123
+ k = self.k_linear(inputs)[..., None, :, :] # (..., head=1, item, hidden_channels)
124
+ v = self.v_linear(inputs)[..., None, :, :]
125
+ return q, k, v
126
+
127
+
128
+ class BaselineSelfAttention(nn.Module):
129
+ """Baseline self-attention layer.
130
+
131
+ Parameters
132
+ ----------
133
+ in_channels : int
134
+ Number of input channels.
135
+ out_channels : int
136
+ Number of input channels.
137
+ hidden_channels : int
138
+ Number of hidden channels = size of query, key, and value.
139
+ num_heads : int
140
+ Number of attention heads.
141
+ pos_encoding : bool
142
+ Whether to apply rotary positional embeddings along the item dimension to the scalar keys
143
+ and queries.
144
+ pos_enc_base : int
145
+ Maximum frequency used in positional encodings. (The minimum frequency is always 1.)
146
+ multi_query : bool
147
+ Use multi-query attention instead of multi-head attention.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ in_channels: int,
153
+ out_channels: int,
154
+ hidden_channels: int,
155
+ num_heads: int = 8,
156
+ pos_encoding: bool = False,
157
+ pos_enc_base: int = 4096,
158
+ multi_query: bool = True,
159
+ ) -> None:
160
+ super().__init__()
161
+
162
+ # Store settings
163
+ self.num_heads = num_heads
164
+ self.hidden_channels = hidden_channels
165
+
166
+ # Linear maps
167
+ qkv_class = MultiQueryQKVLinear if multi_query else MultiHeadQKVLinear
168
+ self.qkv_linear = qkv_class(in_channels, hidden_channels, num_heads)
169
+ self.out_linear = nn.Linear(hidden_channels * num_heads, out_channels)
170
+
171
+ # Optional positional encoding
172
+ if pos_encoding:
173
+ self.pos_encoding = ApplyRotaryPositionalEncoding(
174
+ hidden_channels, item_dim=-2, base=pos_enc_base
175
+ )
176
+ else:
177
+ self.pos_encoding = None
178
+
179
+ def forward(
180
+ self, inputs: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
181
+ ) -> torch.Tensor:
182
+ """Forward pass.
183
+
184
+ Parameters
185
+ ----------
186
+ inputs : Tensor
187
+ Input data
188
+ attention_mask : None or Tensor or xformers.ops.AttentionBias
189
+ Optional attention mask
190
+
191
+ Returns
192
+ -------
193
+ outputs : Tensor
194
+ Outputs
195
+ """
196
+ q, k, v = self.qkv_linear(inputs) # each: (..., num_heads, num_items, num_channels, 16)
197
+
198
+ # Rotary positional encoding
199
+ if self.pos_encoding is not None:
200
+ q = self.pos_encoding(q)
201
+ k = self.pos_encoding(k)
202
+
203
+ # Attention layer
204
+ h = self._attend(q, k, v, attention_mask)
205
+
206
+ # Concatenate heads and transform linearly
207
+ h = rearrange(
208
+ h,
209
+ "... num_heads num_items hidden_channels -> ... num_items (num_heads hidden_channels)",
210
+ )
211
+ outputs = self.out_linear(h) # (..., num_items, out_channels)
212
+
213
+ return outputs
214
+
215
+ @staticmethod
216
+ def _attend(q, k, v, attention_mask=None):
217
+ """Scaled dot-product attention."""
218
+
219
+ # Add batch dimension if needed
220
+ bh_shape = q.shape[:-2]
221
+ q = to_nd(q, 4)
222
+ k = to_nd(k, 4)
223
+ v = to_nd(v, 4)
224
+
225
+ # SDPA
226
+ outputs = scaled_dot_product_attention(
227
+ q.contiguous(), k.expand_as(q).contiguous(), v.expand_as(q), attn_mask=attention_mask
228
+ )
229
+
230
+ # Return batch dimensions to inputs
231
+ outputs = outputs.view(*bh_shape, *outputs.shape[-2:])
232
+
233
+ return outputs
234
+
235
+
236
+ class BaselineTransformerBlock(nn.Module):
237
+ """Baseline transformer block.
238
+
239
+ Inputs are first processed by a block consisting of LayerNorm, multi-head self-attention, and
240
+ residual connection. Then the data is processed by a block consisting of another LayerNorm, an
241
+ item-wise two-layer MLP with GeLU activations, and another residual connection.
242
+
243
+ Parameters
244
+ ----------
245
+ channels : int
246
+ Number of input and output channels.
247
+ num_heads : int
248
+ Number of attention heads.
249
+ pos_encoding : bool
250
+ Whether to apply rotary positional embeddings along the item dimension to the scalar keys
251
+ and queries.
252
+ pos_encoding_base : int
253
+ Maximum frequency used in positional encodings. (The minimum frequency is always 1.)
254
+ increase_hidden_channels : int
255
+ Factor by which the key, query, and value size is increased over the default value of
256
+ hidden_channels / num_heads.
257
+ multi_query : bool
258
+ Use multi-query attention instead of multi-head attention.
259
+ """
260
+
261
+ def __init__(
262
+ self,
263
+ channels,
264
+ num_heads: int = 8,
265
+ pos_encoding: bool = False,
266
+ pos_encoding_base: int = 4096,
267
+ increase_hidden_channels=1,
268
+ multi_query: bool = True,
269
+ ) -> None:
270
+ super().__init__()
271
+
272
+ self.norm = BaselineLayerNorm()
273
+
274
+ # When using positional encoding, the number of scalar hidden channels needs to be even.
275
+ # It also should not be too small.
276
+ hidden_channels = channels // num_heads * increase_hidden_channels
277
+ if pos_encoding:
278
+ hidden_channels = (hidden_channels + 1) // 2 * 2
279
+ hidden_channels = max(hidden_channels, 16)
280
+
281
+ self.attention = BaselineSelfAttention(
282
+ channels,
283
+ channels,
284
+ hidden_channels,
285
+ num_heads=num_heads,
286
+ pos_encoding=pos_encoding,
287
+ pos_enc_base=pos_encoding_base,
288
+ multi_query=multi_query,
289
+ )
290
+
291
+ self.mlp = nn.Sequential(
292
+ nn.Linear(channels, 2 * channels),
293
+ nn.GELU(),
294
+ nn.Linear(2 * channels, channels),
295
+ )
296
+
297
+ def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor:
298
+ """Forward pass.
299
+
300
+ Parameters
301
+ ----------
302
+ inputs : Tensor
303
+ Input data
304
+ attention_mask : None or Tensor or xformers.ops.AttentionBias
305
+ Optional attention mask
306
+
307
+ Returns
308
+ -------
309
+ outputs : Tensor
310
+ Outputs
311
+ """
312
+
313
+ # Residual attention
314
+ h = self.norm(inputs)
315
+ h = self.attention(h, attention_mask)
316
+ outputs = inputs + h
317
+
318
+ # Residual MLP
319
+ h = self.norm(outputs)
320
+ h = self.mlp(h)
321
+ outputs = outputs + h
322
+
323
+ return outputs
324
+
325
+
326
+ class BaselineTransformer(nn.Module):
327
+ """Baseline transformer.
328
+
329
+ Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an
330
+ MLP, residual connections, and normalization layers.
331
+
332
+ Parameters
333
+ ----------
334
+ in_channels : int
335
+ Number of input channels.
336
+ out_channels : int
337
+ Number of output channels.
338
+ hidden_channels : int
339
+ Number of hidden channels.
340
+ num_blocks : int
341
+ Number of transformer blocks.
342
+ num_heads : int
343
+ Number of attention heads.
344
+ pos_encoding : bool
345
+ Whether to apply rotary positional embeddings along the item dimension to the scalar keys
346
+ and queries.
347
+ pos_encoding_base : int
348
+ Maximum frequency used in positional encodings. (The minimum frequency is always 1.)
349
+ increase_hidden_channels : int
350
+ Factor by which the key, query, and value size is increased over the default value of
351
+ hidden_channels / num_heads.
352
+ multi_query : bool
353
+ Use multi-query attention instead of multi-head attention.
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ in_channels: int,
359
+ out_channels: int,
360
+ hidden_channels: int,
361
+ num_blocks: int = 10,
362
+ num_heads: int = 8,
363
+ pos_encoding: bool = False,
364
+ pos_encoding_base: int = 4096,
365
+ checkpoint_blocks: bool = False,
366
+ increase_hidden_channels=1,
367
+ multi_query: bool = False,
368
+ ) -> None:
369
+ super().__init__()
370
+ self.checkpoint_blocks = checkpoint_blocks
371
+ self.linear_in = nn.Linear(in_channels, hidden_channels)
372
+ self.blocks = nn.ModuleList(
373
+ [
374
+ BaselineTransformerBlock(
375
+ hidden_channels,
376
+ num_heads=num_heads,
377
+ pos_encoding=pos_encoding,
378
+ pos_encoding_base=pos_encoding_base,
379
+ increase_hidden_channels=increase_hidden_channels,
380
+ multi_query=multi_query,
381
+ )
382
+ for _ in range(num_blocks)
383
+ ]
384
+ )
385
+ self.linear_out = nn.Linear(hidden_channels, out_channels)
386
+
387
+ def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor:
388
+ """Forward pass.
389
+
390
+ Parameters
391
+ ----------
392
+ inputs : Tensor with shape (..., num_items, num_channels)
393
+ Input data
394
+ attention_mask : None or Tensor or xformers.ops.AttentionBias
395
+ Optional attention mask
396
+
397
+ Returns
398
+ -------
399
+ outputs : Tensor with shape (..., num_items, num_channels)
400
+ Outputs
401
+ """
402
+ h = self.linear_in(inputs)
403
+ for block in self.blocks:
404
+ if self.checkpoint_blocks:
405
+ fn = partial(block, attention_mask=attention_mask)
406
+ h = checkpoint(fn, h)
407
+ else:
408
+ h = block(h, attention_mask=attention_mask)
409
+ outputs = self.linear_out(h)
410
+ return outputs
411
+
412
+
413
+ class BaselineAxialTransformer(nn.Module):
414
+ """Baseline axial transformer for data with two token dimensions.
415
+
416
+ Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an
417
+ MLP, residual connections, and normalization layers.
418
+
419
+ Assumes input data with shape `(..., num_items_1, num_items_2, num_channels, [16])`.
420
+
421
+ The first, third, fifth, ... block computes attention over the `items_2` axis. The other blocks
422
+ compute attention over the `items_1` axis. Positional encoding can be specified separately for
423
+ both axes.
424
+
425
+ Parameters
426
+ ----------
427
+ in_channels : int
428
+ Number of input channels.
429
+ out_channels : int
430
+ Number of output channels.
431
+ hidden_channels : int
432
+ Number of hidden channels.
433
+ num_blocks : int
434
+ Number of transformer blocks.
435
+ num_heads : int
436
+ Number of attention heads.
437
+ pos_encodings : tuple of bool
438
+ Whether to apply rotary positional embeddings along the item dimensions to the scalar keys
439
+ and queries.
440
+ pos_encoding_base : int
441
+ Maximum frequency used in positional encodings. (The minimum frequency is always 1.)
442
+ collapse_dims : tuple of bool
443
+ Whether batch and token dimensions will be collapsed to support xformers block attention.
444
+ The first element of this tuple describes the behaviour in the 0th, 2nd, ... block, the
445
+ second element in the 1st, 3rd, ... block (where the axes are reversed).
446
+ """
447
+
448
+ def __init__(
449
+ self,
450
+ in_channels: int,
451
+ out_channels: int,
452
+ hidden_channels: int,
453
+ num_blocks: int = 20,
454
+ num_heads: int = 8,
455
+ pos_encodings: Tuple[bool, bool] = (False, False),
456
+ pos_encoding_base: int = 4096,
457
+ collapse_dims: Tuple[bool, bool] = (False, False),
458
+ ) -> None:
459
+ super().__init__()
460
+ self.linear_in = nn.Linear(in_channels, hidden_channels)
461
+ self.blocks = nn.ModuleList(
462
+ [
463
+ BaselineTransformerBlock(
464
+ hidden_channels,
465
+ num_heads=num_heads,
466
+ pos_encoding=pos_encodings[(block + 1) % 2],
467
+ pos_encoding_base=pos_encoding_base,
468
+ )
469
+ for block in range(num_blocks)
470
+ ]
471
+ )
472
+ self.linear_out = nn.Linear(hidden_channels, out_channels)
473
+ self._collapse_dims_for_even_blocks, self._collapse_dims_for_odd_blocks = collapse_dims
474
+
475
+ def forward(self, inputs: torch.Tensor, attention_mask: Optional[Tuple] = None) -> torch.Tensor:
476
+ """Forward pass.
477
+
478
+ Parameters
479
+ ----------
480
+ inputs : Tensor with shape (..., num_items1, num_items2, num_channels)
481
+ Input data
482
+ attention_mask : None or tuple of torch.Tensor
483
+ Optional attention masks
484
+
485
+ Returns
486
+ -------
487
+ outputs : Tensor with shape (..., num_items1, num_items2, num_channels)
488
+ Outputs
489
+ """
490
+
491
+ h = self.linear_in(inputs)
492
+
493
+ for i, block in enumerate(self.blocks):
494
+ # For first, third, ... block, we want to perform attention over the first token
495
+ # dimension. We implement this by transposing the two item dimensions.
496
+ if i % 2 == 1:
497
+ h, input_batch_dims = self._reshape_data_before_odd_blocks(h)
498
+ else:
499
+ h, input_batch_dims = self._reshape_data_before_even_blocks(h)
500
+
501
+ # Attention masks will also be different
502
+ if attention_mask is None:
503
+ this_attention_mask = None
504
+ else:
505
+ this_attention_mask = attention_mask[(i + 1) % 2]
506
+
507
+ h = block(h, attention_mask=this_attention_mask)
508
+
509
+ # Transposing back to standard axis order
510
+ if i % 2 == 1:
511
+ h = self._reshape_data_after_odd_blocks(h, input_batch_dims)
512
+ else:
513
+ h = self._reshape_data_after_even_blocks(h, input_batch_dims)
514
+
515
+ outputs = self.linear_out(h)
516
+
517
+ return outputs
518
+
519
+ def _reshape_data_before_odd_blocks(self, h):
520
+ # Transpose token axes
521
+ h = rearrange(h, _REARRANGE_PATTERN) # (axis2, axis1, ...)
522
+
523
+ # Prepare uncollapsing
524
+ input_batch_dims = h.shape[:2]
525
+
526
+ # Collapse dimensions
527
+ if self._collapse_dims_for_odd_blocks:
528
+ h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...)
529
+
530
+ return h, input_batch_dims
531
+
532
+ def _reshape_data_after_odd_blocks(self, h, input_batch_dims):
533
+ # Uncollapse
534
+ if self._collapse_dims_for_odd_blocks:
535
+ h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...)
536
+
537
+ # Re-transpose token axes
538
+ h = rearrange(h, _REARRANGE_PATTERN) # (axis1, axis2, ...)
539
+
540
+ return h
541
+
542
+ def _reshape_data_before_even_blocks(self, h):
543
+ # Prepare un-collapsing
544
+ input_batch_dims = h.shape[:2]
545
+
546
+ # Collapse
547
+ if self._collapse_dims_for_even_blocks:
548
+ h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...)
549
+
550
+ return h, input_batch_dims
551
+
552
+ def _reshape_data_after_even_blocks(self, h, input_batch_dims):
553
+ # Uncollapse
554
+ if self._collapse_dims_for_even_blocks:
555
+ h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...)
556
+
557
+ return h
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .base_experiment import BaseExperiment
4
+ from .base_wrapper import BaseWrapper
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .dataset import InMemoryVesselDataset, NumberedVesselDataset, RotationDataset
4
+ from .experiment import ArteryExperiment
5
+ from .wrappers import ArteryBaselineWrapper, ArteryGATrWrapper
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/dataset.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import os
4
+ import re
5
+
6
+ import numpy as np
7
+ import scipy
8
+ import torch
9
+ from coronary_mesh_convolution.datasets import InMemoryVesselDataset
10
+ from torch.utils.data import Dataset
11
+
12
+
13
+ class NumberedVesselDataset(InMemoryVesselDataset):
14
+ """Artery dataset with added shape id attribute."""
15
+
16
+ @staticmethod
17
+ def load_process_hdf5(path):
18
+ """Wrap super method with adding shape id."""
19
+ _, sample = os.path.split(path)
20
+ data = InMemoryVesselDataset.load_process_hdf5(path)
21
+ data.shape_id = int(re.match(r"sample_(\d+)", sample).group(1))
22
+ return data
23
+
24
+
25
+ class RotationDataset(Dataset):
26
+ """A dataset containing random (S)O(3) elements.
27
+
28
+ Parameters
29
+ ----------
30
+ num : int
31
+ Size of the dataset (number of rotations)
32
+ special : bool
33
+ If True, samples from the Haar measure on SO(3); otherwise, on O(3)
34
+ seed : int
35
+ numpy random seed
36
+ """
37
+
38
+ def __init__(self, num, special, seed):
39
+ super().__init__()
40
+ if special:
41
+ sampler = scipy.stats.special_ortho_group
42
+ else:
43
+ sampler = scipy.stats.ortho_group
44
+ random_state = np.random.RandomState(seed=seed)
45
+ self.data = torch.tensor(
46
+ sampler.rvs(3, size=num, random_state=random_state), dtype=torch.float32
47
+ )
48
+
49
+ def __len__(self):
50
+ """Dataset size."""
51
+ return len(self.data)
52
+
53
+ def __getitem__(self, idx):
54
+ """Return an item from the dataset."""
55
+ return self.data[idx]
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/experiment.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from pathlib import Path
4
+
5
+ import pandas as pd
6
+ import torch
7
+ import torch_geometric
8
+ from coronary_mesh_convolution.transforms import InletGeodesics, RemoveFlowExtensions
9
+ from coronary_mesh_convolution.utils.metrics import Metrics
10
+
11
+ from gatr.experiments import BaseExperiment
12
+ from gatr.experiments.arteries.dataset import NumberedVesselDataset, RotationDataset
13
+ from gatr.utils.logger import logger
14
+
15
+ LABEL_SCALE = 53.8360 # the sqrt of average squared norm of training label vectors
16
+
17
+
18
+ class ArteryExperiment(BaseExperiment):
19
+ """Experiment manager for wall-shear-stress estimation in arteries.
20
+
21
+ The dataset was introduced and is described in Suk et al, "Mesh Convolutional Neural Networks
22
+ for Wall Shear Stress Estimation in 3D Artery Models".
23
+
24
+ References
25
+ ----------
26
+ J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in
27
+ 3D Artery Models", arXiv:2109.04797
28
+
29
+ Parameters
30
+ ----------
31
+ cfg : OmegaConf
32
+ Experiment configuration. See the config folder in the repository for examples.
33
+ """
34
+
35
+ def __init__(self, cfg):
36
+ super().__init__(cfg)
37
+ self._criterion = torch.nn.MSELoss()
38
+
39
+ # Data transforms
40
+ transforms = [
41
+ torch_geometric.transforms.GenerateMeshNormals(),
42
+ InletGeodesics(),
43
+ RemoveFlowExtensions(factor=(4.0, 1.0)),
44
+ ]
45
+ self.transform = torch_geometric.transforms.Compose(transforms)
46
+ self.rotations = RotationDataset(2000, special=False, seed=123)
47
+
48
+ def rotate_sample(self, data):
49
+ """Rotate data sample with pre-sampled rotation matrices."""
50
+ r = self.rotations[data.shape_id[0]]
51
+ data.pos = data.pos @ r.T
52
+ data.norm = data.norm @ r.T
53
+ data.y = data.y @ r.T
54
+ return data
55
+
56
+ def _load_dataset(self, tag):
57
+ """Loads dataset.
58
+
59
+ References
60
+ ----------
61
+ J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in
62
+ 3D Artery Models", arXiv:2109.04797
63
+
64
+ Parameters
65
+ ----------
66
+ tag : str
67
+ Dataset tag, like "train", "val", or one of self._eval_tags.
68
+
69
+ Returns
70
+ -------
71
+ dataset : torch.utils.data.Dataset
72
+ Dataset.
73
+ """
74
+
75
+ # Train / validation / test splits from Suk et al
76
+ split = {"train": [0, 1600], "val": [1600, 1799], "eval": [1799, 1999]}[tag]
77
+
78
+ if (self.cfg.data.rotate_train and tag == "train") or (
79
+ self.cfg.data.rotate_test and tag in ["val", "eval"]
80
+ ):
81
+ transform = self.rotate_sample
82
+ else:
83
+ transform = None
84
+
85
+ # Load dataset
86
+ dataset = NumberedVesselDataset(
87
+ Path(self.cfg.data.data_dir),
88
+ "*.hdf5",
89
+ split,
90
+ tag,
91
+ pre_transform=self.transform,
92
+ transform=transform,
93
+ )
94
+
95
+ # Subsample dataset if requested
96
+ if tag == "train" and self.cfg.data.subsample is not None and self.cfg.data.subsample < 1.0:
97
+ n = int(round(self.cfg.data.subsample * len(dataset)))
98
+ dataset = dataset.index_select(slice(n))
99
+
100
+ # Logging
101
+ logger.info(f"Loaded dataset partition {tag} with length {len(dataset)}")
102
+
103
+ return dataset
104
+
105
+ def _prep_data(self, data, device=None):
106
+ """Data preparation during training loop, e.g. to move data to correct device and dtype."""
107
+
108
+ if device is None:
109
+ device = self.device
110
+
111
+ # Only move relevant features to GPU and float16
112
+ data.pos = data.pos.to(device)
113
+ data.norm = data.norm.to(device)
114
+ data.geo = data.geo.to(device)
115
+ data.y = data.y.to(device)
116
+
117
+ # NaN debugging
118
+ assert torch.all(torch.isfinite(data.pos))
119
+ assert torch.all(torch.isfinite(data.norm))
120
+ assert torch.all(torch.isfinite(data.geo))
121
+ assert torch.all(torch.isfinite(data.y))
122
+
123
+ # Mask should also be on GPU, but remain as bool
124
+ data.mask = data.mask.to(device)
125
+ data.batch = data.batch.to(device)
126
+
127
+ return (data,)
128
+
129
+ def _forward(self, *data):
130
+ """Model forward pass.
131
+
132
+ Parameters
133
+ ----------
134
+ data : tuple of torch.Tensor
135
+ Data batch.
136
+
137
+ Returns
138
+ -------
139
+ loss : torch.Tensor
140
+ Loss
141
+ metrics : dict with str keys and float values
142
+ Additional metrics for logging
143
+ """
144
+
145
+ # Forward pass
146
+ assert self.model is not None
147
+ data = data[0]
148
+ y_pred = self.model(data)
149
+
150
+ # NaN debugging
151
+ assert torch.all(torch.isfinite(y_pred))
152
+
153
+ # Compute loss
154
+ y = data.y.view(*y_pred.shape)
155
+ y_normalized = y / LABEL_SCALE # normalize labels
156
+ y_pred_unnormalized = y_pred * LABEL_SCALE # unnormalize predictions
157
+ mse_normalized = self._criterion(y_pred[:, data.mask, :], y_normalized[:, data.mask, :])
158
+ mse = self._criterion(y_pred_unnormalized[:, data.mask, :], y[:, data.mask, :])
159
+ loss = mse_normalized
160
+
161
+ # Additional metrics
162
+ metrics = dict(mse=mse.item(), mse_normalized=mse_normalized.item())
163
+
164
+ return loss, metrics
165
+
166
+ @torch.no_grad()
167
+ def _compute_metrics(self, dataloader):
168
+ """Given a dataloader, computes all relevant metrics. To be implemented by subclasses.
169
+
170
+ Parameters
171
+ ----------
172
+ dataloader : torch.utils.data.DataLoader
173
+ Dataloader.
174
+
175
+ Returns
176
+ -------
177
+ metrics : dict with str keys and float values
178
+ Metrics computed from dataset.
179
+ """
180
+
181
+ # Move to eval mode and eval device
182
+ assert self.model is not None
183
+ self.model.eval()
184
+ eval_device = torch.device(self.cfg.training.eval_device)
185
+ self.model = self.model.to(eval_device)
186
+
187
+ metrics_model = Metrics([dataloader])
188
+ results = []
189
+
190
+ # Loop over dataset and compute metrics
191
+ for data in dataloader:
192
+ data = self._prep_data(data)[0]
193
+ model_output = self.model(data)
194
+ y_pred_batch = model_output[0] * LABEL_SCALE # Scale as ground truth, remove batch idx
195
+ num_meshes = data.batch.max() + 1
196
+ for mesh_i in range(num_meshes):
197
+ batch_mask = data.batch == mesh_i
198
+ # Mask out one particular mesh, remove the in/outlets
199
+ prediction = y_pred_batch[batch_mask & data.mask]
200
+ label = data.y[batch_mask & data.mask]
201
+ _, maximum, mean, _ = metrics_model.absolute_differences(prediction, label)
202
+ scale_max, scale_median = metrics_model.scale(label)
203
+ approximation_error = metrics_model.approximation_error(prediction, label)
204
+ mse = self._criterion(prediction, label)
205
+ mesh_results = dict(
206
+ delta_max=maximum.item(),
207
+ delta_mean=mean.item(),
208
+ nmae=(mean / metrics_model.M).item(),
209
+ approximation_error=approximation_error.item(),
210
+ scale_max=scale_max.item(),
211
+ scale_median=scale_median.item(),
212
+ mse=mse.item(),
213
+ )
214
+ results.append(mesh_results)
215
+ df = pd.DataFrame(results)
216
+ metrics = {}
217
+ for metric, series in df.items():
218
+ metrics[f"{metric}"] = series.mean()
219
+ metrics[f"{metric}_median"] = series.median()
220
+ metrics[f"{metric}_q75"] = series.quantile(0.75)
221
+ metrics["loss"] = metrics["mse"]
222
+
223
+ # Move model back to training mode and training device
224
+ self.model.train()
225
+ self.model = self.model.to(self.device)
226
+
227
+ return metrics
228
+
229
+ @property
230
+ def _eval_dataset_tags(self):
231
+ """Eval dataset tags.
232
+
233
+ Returns
234
+ -------
235
+ tags : iterable of str
236
+ Eval dataset tags
237
+ """
238
+ return {"eval"}
239
+
240
+ def _make_data_loader(self, dataset, batch_size, shuffle):
241
+ """Creates a data loader.
242
+
243
+ Parameters
244
+ ----------
245
+ dataset : torch.nn.utils.data.Dataset
246
+ Dataset.
247
+ batch_size : int
248
+ Batch size.
249
+ shuffle : bool
250
+ Whether the dataset is shuffled.
251
+
252
+ Returns
253
+ -------
254
+ dataloader
255
+ Data loader.
256
+ """
257
+ return torch_geometric.data.DataLoader(
258
+ dataset, batch_size=batch_size, shuffle=shuffle, num_workers=0, pin_memory=False
259
+ )
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/wrappers.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+ from torch import nn
5
+ from xformers.ops.fmha import BlockDiagonalMask
6
+
7
+ from gatr.experiments.base_wrapper import BaseWrapper
8
+ from gatr.interface import embed_oriented_plane, embed_point, embed_scalar, extract_translation
9
+
10
+
11
+ def build_attention_mask(inputs):
12
+ """Construct attention mask from pytorch geometric batch.
13
+
14
+ Parameters
15
+ ----------
16
+ inputs : torch_geometric.data.Batch
17
+ Data batch.
18
+
19
+ Returns
20
+ -------
21
+ attention_mask : xformers.ops.fmha.BlockDiagonalMask
22
+ Block-diagonal attention mask: within each sample, each token can attend to each other
23
+ token.
24
+ """
25
+ return BlockDiagonalMask.from_seqlens(torch.bincount(inputs.batch).tolist())
26
+
27
+
28
+ class ArteryBaselineWrapper(nn.Module):
29
+ """Wraps around simple baselines (like a Transformer) for the artery experiment.
30
+
31
+ We use the following parameterization of the artery mesh:
32
+ - the node positions of the arterial mesh
33
+ - the mesh normals
34
+ - the geodesic distance to the inlet
35
+
36
+ Parameters
37
+ ----------
38
+ net : torch.nn.Module
39
+ Model that accepts inputs with 7 channels and returns outputs with 3 channels.
40
+ """
41
+
42
+ def __init__(self, net):
43
+ super().__init__()
44
+ self.net = net
45
+
46
+ def forward(self, inputs):
47
+ """Wrapped forward pass."""
48
+ mask = build_attention_mask(inputs)
49
+ x = torch.cat([inputs.pos, inputs.norm, inputs.geo[:, None]], 1)[None]
50
+ return self.net(x, attention_mask=mask)
51
+
52
+
53
+ class ArteryGATrWrapper(BaseWrapper):
54
+ """Wraps around GATr for the arterial wall-shear-stress prediction experiment.
55
+
56
+ Parameters
57
+ ----------
58
+ net : torch.nn.Module
59
+ GATr model that accepts inputs with 3 multivector channels and 1 scalar channel, and
60
+ returns outputs with 1 multivector channel and 1 scalar channel.
61
+ """
62
+
63
+ def __init__(self, net):
64
+ super().__init__(net, scalars=True, return_other=False)
65
+
66
+ def build_attention_mask(
67
+ self,
68
+ inputs,
69
+ mv=None,
70
+ s=None,
71
+ ):
72
+ """Construct block-diagonal attention mask."""
73
+ return build_attention_mask(inputs)
74
+
75
+ def embed_into_ga(self, inputs):
76
+ """Embeds raw artery data into the geometric algebra.
77
+
78
+ We use the following parameterization of the artery mesh:
79
+ - the node positions of the arterial mesh, represented as points
80
+ - the mesh normals, represented as oriented planes
81
+ - the geodesic distance to the inlet, represented as scalars
82
+
83
+ Parameters
84
+ ----------
85
+ inputs : torch_geometric.data.Batch
86
+ Raw artery data.
87
+
88
+ Returns
89
+ -------
90
+ multivectors : torch.Tensor with shape (batchsize * num_items, num_mv_channels, 16)
91
+ Multivector embeddings of the geometric information in the dataset.
92
+ scalars : torch.Tensor with shape (batchsize * num_items, num_s_channels)
93
+ Auxiliary scalars, which in this dataset are just dummy placeholders.
94
+ """
95
+
96
+ # Get interesting features from PyG object
97
+ num_items = len(inputs.pos)
98
+ pos = inputs.pos.reshape(1, num_items, 1, 3) # (batch, items, channels, 3)
99
+ mesh_normals = inputs.norm.reshape(1, num_items, 1, 3) # (batch, items, channels, 3)
100
+ inlet_distance = inputs.geo.reshape(1, num_items, 1, 1) # (batch, items, channels, 1)
101
+
102
+ # NaN debugging
103
+ assert torch.all(torch.isfinite(pos))
104
+ assert torch.all(torch.isfinite(mesh_normals))
105
+ assert torch.all(torch.isfinite(inlet_distance))
106
+
107
+ # Embed in GA
108
+ positions = embed_point(pos)
109
+ mesh_normals = embed_oriented_plane(mesh_normals, pos)
110
+ inlet_distance = embed_scalar(inlet_distance)
111
+
112
+ # NaN debugging
113
+ assert torch.all(torch.isfinite(positions))
114
+ assert torch.all(torch.isfinite(mesh_normals))
115
+ assert torch.all(torch.isfinite(inlet_distance))
116
+
117
+ # Concatenate along channel dimension
118
+ mv = torch.concatenate(
119
+ [positions, mesh_normals, inlet_distance], dim=2
120
+ ) # (batch, items, 3, 16)
121
+
122
+ # Dummy scalar
123
+ s = torch.zeros(1, num_items, 1, device=mv.device, dtype=mv.dtype)
124
+
125
+ return mv, s
126
+
127
+ def extract_from_ga(self, multivector, scalars):
128
+ """Extracts the predicted wall shear stress from the output multivectors.
129
+
130
+ We parameterize the wall shear stress as translation vectors.
131
+
132
+ Parameters
133
+ ----------
134
+ multivector : torch.Tensor with shape (1, batchsize * num_items, num_mv_channels, 16)
135
+ Multivector outputs.
136
+ scalars : torch.Tensor with shape (1, batchsize * num_items, num_s_channels)
137
+ Scalar outputs.
138
+
139
+ Returns
140
+ -------
141
+ wss : torch.Tensor with shape (1, batchsize * num_items, 3)
142
+ Predicted wall shear stress vectors.
143
+ regularization : None
144
+ Regularization term. As there is no regularizer in this experiment, we return None.
145
+ """
146
+ # Check channels of inputs. Object numbers are free.
147
+ assert multivector.shape[0] == scalars.shape[0] == 1
148
+ assert multivector.shape[2:] == (1, 16)
149
+
150
+ # Extract wall shear stress
151
+ wss = extract_translation(multivector[:, :, 0, :]) # (1, objects, 3)
152
+
153
+ return wss, None
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_experiment.py ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
3
+ # All rights reserved.
4
+
5
+ import logging
6
+ import time
7
+ from collections import defaultdict
8
+ from contextlib import nullcontext
9
+ from pathlib import Path
10
+ from typing import Dict, Optional
11
+
12
+ import matplotlib
13
+ import mlflow
14
+ import numpy as np
15
+ import pandas as pd
16
+ import seaborn as sns
17
+ import torch
18
+ from hydra.core.config_store import ConfigStore
19
+ from hydra.utils import instantiate
20
+ from omegaconf import OmegaConf
21
+ from torch import nn
22
+ from torch.utils.data import DataLoader
23
+ from torch_ema import ExponentialMovingAverage
24
+ from tqdm import tqdm, trange
25
+
26
+ import gatr.primitives.attention
27
+ import gatr.utils.logger
28
+ from gatr.layers import SelfAttentionConfig
29
+ from gatr.layers.mlp.config import MLPConfig
30
+ from gatr.utils.logger import logger
31
+ from gatr.utils.misc import NaNError, flatten_dict, frequency_check, get_batchsize, get_device
32
+ from gatr.utils.mlflow import log_mlflow
33
+ from gatr.utils.plotting import MATPLOTLIB_PARAMS
34
+
35
+ cs = ConfigStore.instance()
36
+ cs.store(name="base_attention", node=SelfAttentionConfig)
37
+ cs.store(name="base_mlp", node=MLPConfig)
38
+
39
+
40
+ class BaseExperiment:
41
+ """Base experiment manager class.
42
+
43
+ To be subclassed by experiment-specific manager classes.
44
+
45
+ Parameters
46
+ ----------
47
+ cfg : OmegaConf
48
+ Experiment configuration. See the config folder in the repository for examples.
49
+ """
50
+
51
+ def __init__(self, cfg):
52
+ # Store config
53
+ self.cfg = cfg
54
+
55
+ # Device, dtype, backend
56
+ self.device, self.dtype = self._init_backend()
57
+
58
+ # Initialize state
59
+ self.model: Optional[nn.Module] = None
60
+ self.ema = None
61
+ self.optim = None
62
+ self.scheduler = None
63
+
64
+ self.metrics = {}
65
+ self._best_state = None
66
+ self._training_start_time: Optional[float] = None
67
+
68
+ # Initialize folder and logger
69
+ self._initialize_experiment_folder()
70
+ self._initialize_logger()
71
+ self._silence_the_lambs()
72
+
73
+ # Training hooks: list of (state, hook_function)
74
+ self._hooks = []
75
+
76
+ def __call__(self, train=True, evaluate=True):
77
+ """Performs experiment as outlined below.
78
+
79
+ - initializes all the logistics
80
+ - instantiates model (if necessary)
81
+ - loads checkpoint (if applicable)
82
+ - trains model (if `train`)
83
+ - evaluates model (if `eval`)
84
+
85
+ Parameters
86
+ ----------
87
+ train : bool
88
+ Whether to train the model.
89
+ evaluate : bool
90
+ Whether to evaluate the model.
91
+ """
92
+
93
+ experiment_id = self._initialize_experiment()
94
+
95
+ with mlflow.start_run(experiment_id=experiment_id, run_name=self.cfg.run_name):
96
+ self._save_config()
97
+
98
+ # Create / load model
99
+ if self.model is None:
100
+ self.create_model()
101
+ self.load_model()
102
+
103
+ # Train
104
+ if train:
105
+ self.train()
106
+ # Save model
107
+ self.save_model("model_final.pt")
108
+
109
+ # Evaluate
110
+ if evaluate:
111
+ self.evaluate()
112
+
113
+ logger.info("Anders nog iets?")
114
+ return self.metrics
115
+
116
+ def create_model(self):
117
+ """Create self.model according to the specification in self.cfg."""
118
+
119
+ # Create model
120
+ self.model = self._create_model()
121
+ assert self.model is not None
122
+ self.optim, self.scheduler = self._create_optimizer_and_scheduler()
123
+
124
+ # Report number of parameters
125
+ num_parameters = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
126
+ log_mlflow("efficiency.num_parameters", float(num_parameters), step=0)
127
+ logger.info(f"Model has {num_parameters / 1e6:.2f}M learnable parameters")
128
+
129
+ # Create exponential moving average object
130
+ if self.cfg.training.ema:
131
+ logger.info("Using EMA for validation and eval")
132
+ self.ema = ExponentialMovingAverage(
133
+ self.model.parameters(), decay=self.cfg.training.ema_decay
134
+ )
135
+ else:
136
+ logger.debug("Not using EMA")
137
+ self.ema = None
138
+
139
+ def load_model(self, checkpoint=None):
140
+ """Loads a model checkpoint from disk.
141
+
142
+ Parameters
143
+ ----------
144
+ checkpoint : None or str or pathlib.Path
145
+ Path to checkpoint. If None, self.cfg.checkpoint is used.
146
+ """
147
+
148
+ # If model hasn't been created yet, do that first
149
+ if self.model is None:
150
+ self.create_model()
151
+ assert self.model is not None
152
+
153
+ if checkpoint is None:
154
+ checkpoint = self.cfg.checkpoint
155
+
156
+ if checkpoint is not None:
157
+ logger.info(f"Loading model checkpoint from {checkpoint}")
158
+ state_dict = torch.load(checkpoint, map_location="cpu")
159
+ self.model.load_state_dict(state_dict)
160
+
161
+ if self.cfg.training.ema:
162
+ ema_checkpoint = checkpoint.replace(".pt", "_ema.pt")
163
+ logger.info(f"Loading EMA checkpoint from {ema_checkpoint}")
164
+ state_dict = torch.load(ema_checkpoint, map_location="cpu")
165
+ assert self.ema is not None
166
+ self.ema.load_state_dict(state_dict)
167
+
168
+ def train(self):
169
+ """High-level training function."""
170
+ assert self.model is not None
171
+
172
+ logger.info("Starting training")
173
+
174
+ # Prepare data
175
+ train_data = self._load_dataset("train")
176
+ train_loader = self._make_data_loader(
177
+ train_data, batch_size=self.cfg.training.batchsize, shuffle=True
178
+ )
179
+ val_data = self._load_dataset("val")
180
+ eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize)
181
+ val_loader = self._make_data_loader(val_data, batch_size=eval_batchsize, shuffle=False)
182
+
183
+ # Training
184
+ num_epochs = (self.cfg.training.steps - 1) // (
185
+ (len(train_data) - 1) // self.cfg.training.batchsize + 1
186
+ ) + 1
187
+ logger.info(
188
+ f"Training for {self.cfg.training.steps} steps, that is, {num_epochs} epochs on a "
189
+ f"dataset of size {len(train_data)} with batchsize {self.cfg.training.batchsize}"
190
+ )
191
+
192
+ # Prepare book-keeping
193
+ self._best_state = {"state_dict": None, "loss": None, "step": None}
194
+ self._training_start_time = time.time()
195
+
196
+ # GPU
197
+ self.model = self.model.to(self.device)
198
+ if self.ema:
199
+ self.ema.to(self.device)
200
+
201
+ # Loop over epochs
202
+ step = 0
203
+ for epoch in trange(
204
+ num_epochs, desc="Training epochs", disable=not self.cfg.training.progressbar
205
+ ):
206
+ log_mlflow("train.epoch", epoch, step=step)
207
+ epoch_start = time.perf_counter()
208
+ self.model.train()
209
+
210
+ # Loop over steps
211
+ for data in train_loader:
212
+ self._step(data, step, val_data, val_loader)
213
+ if step >= self.cfg.training.steps:
214
+ break
215
+ step += 1
216
+
217
+ logger.debug(f"Finished epoch {epoch} in {time.perf_counter() - epoch_start} seconds")
218
+
219
+ logger.debug("Finished training")
220
+
221
+ # Final validation loop
222
+ if (
223
+ self.cfg.training.validate_every_n_steps is not None
224
+ and self.cfg.training.validate_every_n_steps > 0
225
+ ):
226
+ self.validate(val_loader, step)
227
+
228
+ # Wrap up early stopping
229
+ if (
230
+ self.cfg.training.early_stopping
231
+ and self._best_state["step"] is not None
232
+ and self._best_state["step"] < step
233
+ ):
234
+ logger.info(
235
+ f'Early stopping after step {self._best_state["step"]} '
236
+ f'with validation loss {self._best_state["loss"]}'
237
+ )
238
+ self.model.load_state_dict(self._best_state["state_dict"])
239
+ else:
240
+ logger.debug("Not using early stopping")
241
+
242
+ def validate(self, dataloader, step):
243
+ """Runs validation loop, logs results, and may store state dict for early stopping.
244
+
245
+ Parameters
246
+ ----------
247
+ dataloader : torch.utils.data.DataLoader
248
+ Validation dataloader.
249
+ step : int
250
+ Current step number.
251
+ """
252
+ assert self.model is not None
253
+
254
+ # Compute validation metrics, using EMA if available
255
+ if self.ema is not None:
256
+ with self.ema.average_parameters():
257
+ metrics = self._compute_metrics(dataloader)
258
+ else:
259
+ metrics = self._compute_metrics(dataloader)
260
+
261
+ # Log
262
+ self.metrics["val"] = metrics
263
+ logger.info(f"Validation loop at step {step}:")
264
+ for key, value in metrics.items():
265
+ log_mlflow(f"val.{key}", value, step=step)
266
+ logger.info(f" {key} = {value}")
267
+
268
+ # Early stopping: compare val loss to last val loss
269
+ new_val_loss = metrics["loss"]
270
+ assert self._best_state is not None
271
+ if self._best_state["loss"] is None or new_val_loss < self._best_state["loss"]:
272
+ self._best_state["loss"] = new_val_loss
273
+ self._best_state["state_dict"] = self.model.state_dict().copy()
274
+ self._best_state["step"] = step
275
+
276
+ def evaluate(self):
277
+ """Evaluates self.model on all eval datasets and logs the results."""
278
+
279
+ # Should we evaluate with EMA in addition to without?
280
+ ema_values = [False]
281
+ if self.ema is not None:
282
+ ema_values.append(True)
283
+
284
+ # Loop over evaluation datasets
285
+ dfs = {}
286
+ for tag in self._eval_dataset_tags:
287
+ dataset = self._load_dataset(tag)
288
+ eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize)
289
+ dataloader = self._make_data_loader(dataset, batch_size=eval_batchsize, shuffle=False)
290
+
291
+ # Loop over EMA on / off
292
+ for ema in ema_values:
293
+ # Effective tag name
294
+ full_tag = (tag + "_ema") if ema else tag
295
+
296
+ # Run evaluation
297
+ if ema:
298
+ with self.ema.average_parameters():
299
+ metrics = self._compute_metrics(dataloader)
300
+ else:
301
+ metrics = self._compute_metrics(dataloader)
302
+
303
+ # Log results
304
+ self.metrics[full_tag] = metrics
305
+ logger.info(f"Ran evaluation on dataset {full_tag}:")
306
+ for key, val in metrics.items():
307
+ logger.info(f" {key} = {val}")
308
+ log_mlflow(f"eval.{full_tag}.{key}", val)
309
+
310
+ # Store results in csv file
311
+ # Pandas does not like scalar values, have to be iterables
312
+ test_metrics_ = {key: [val] for key, val in metrics.items()}
313
+ df = pd.DataFrame.from_dict(test_metrics_)
314
+ df.to_csv(Path(self.cfg.exp_dir) / "metrics" / f"eval_{full_tag}.csv", index=False)
315
+ dfs[full_tag] = df
316
+ return dfs
317
+
318
+ def save_model(self, filename=None):
319
+ """Save model in experiment folder.
320
+
321
+ Parameters
322
+ ----------
323
+ filename : None or str
324
+ Filename to save the model to.
325
+ """
326
+
327
+ assert self.model is not None
328
+ if filename is None:
329
+ filename = "model.pt"
330
+
331
+ model_path = Path(self.cfg.exp_dir) / "models" / filename
332
+ logger.info(f"Saving model at {model_path}")
333
+ torch.save(self.model.state_dict(), model_path)
334
+
335
+ if self.ema is not None:
336
+ ema_path = Path(self.cfg.exp_dir) / "models" / filename.replace(".pt", "_ema.pt")
337
+ logger.debug(f"Saving EMA model at {ema_path}")
338
+ assert ema_path != model_path
339
+ torch.save(self.ema.state_dict(), ema_path)
340
+
341
+ def register_hook(self, function, step=None, every_steps=None):
342
+ """Registers a hook.
343
+
344
+ Hooks are functions called either at a specific step or every n steps during training.
345
+ """
346
+ assert (step is None) != (every_steps is None)
347
+ self._hooks.append((step, every_steps, function))
348
+
349
+ def _init_backend(self):
350
+ """Initializes device, dtype, and attention implementation."""
351
+
352
+ # Device
353
+ device = get_device()
354
+ logger.debug(f"Training on {device}")
355
+
356
+ # Dtype
357
+ if self.cfg.training.float16 and torch.cuda.is_bf16_supported():
358
+ dtype = torch.bfloat16
359
+ logger.info("Training on bfloat16")
360
+ elif self.cfg.training.float16:
361
+ dtype = torch.float16
362
+ logger.info("Training on float16 (bfloat16 is not supported by environment)")
363
+ else:
364
+ dtype = torch.float32
365
+ logger.info("Training on float32")
366
+
367
+ # Attention implementation
368
+ torch.backends.cuda.enable_flash_sdp(self.cfg.training.enable_flash_sdp)
369
+ torch.backends.cuda.enable_math_sdp(self.cfg.training.enable_math_sdp)
370
+ torch.backends.cuda.enable_mem_efficient_sdp(self.cfg.training.enable_mem_efficient_sdp)
371
+ if self.cfg.training.force_xformers:
372
+ logger.debug("Forcing use of xformers' attention implementation")
373
+ gatr.primitives.attention.FORCE_XFORMERS = True
374
+
375
+ return device, dtype
376
+
377
+ def _initialize_experiment(self):
378
+ """Initialize experiment folder (and plenty of other initialization thingies)."""
379
+
380
+ # Initialize MLflow experiment
381
+ experiment_id = self._initialize_mlflow()
382
+
383
+ # Silence other loggers (thanks MLflow)
384
+ self._silence_the_lambs()
385
+
386
+ # Re-initialize logger - this is annoying, something in the way that MLflow interacts with
387
+ # logging means that we otherwise get duplicate logging to stdout
388
+ self._initialize_logger()
389
+
390
+ # Print config to log
391
+ logger.info(f"Running experiment at {self.cfg.exp_dir}")
392
+ logger.debug(f"Config: \n{OmegaConf.to_yaml(self.cfg)}")
393
+
394
+ # Set random seed
395
+ torch.random.manual_seed(self.cfg.seed)
396
+ np.random.seed(self.cfg.seed)
397
+
398
+ # Initialize plotting
399
+ self._init_plt()
400
+
401
+ return experiment_id
402
+
403
+ def _initialize_experiment_folder(self):
404
+ """Creates experiment folder."""
405
+
406
+ exp_dir = Path(self.cfg.exp_dir).resolve()
407
+ subfolders = [
408
+ exp_dir / "models",
409
+ exp_dir / "figures",
410
+ exp_dir / "metrics",
411
+ exp_dir / "data",
412
+ ]
413
+
414
+ # Create experiment subfolders (main folder will be automatically created as well)
415
+ for subdir in subfolders:
416
+ if subdir.exists():
417
+ logger.warning(f"Warning: directory {subdir} already exists!")
418
+ subdir.mkdir(parents=True, exist_ok=True)
419
+
420
+ def _initialize_logger(self):
421
+ """Initializes logging."""
422
+
423
+ # In sweeps (multiple experiments in one job) we don't want to set up the handlers again
424
+ if gatr.utils.logger.logging_initialized:
425
+ logger.info("Logger already initialized - hi again!")
426
+ return
427
+
428
+ logger.setLevel(logging.DEBUG if self.cfg.debug else logging.INFO)
429
+ formatter = logging.Formatter(
430
+ "[%(asctime)-19.19s %(levelname)-1.1s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
431
+ )
432
+
433
+ file_handler = logging.FileHandler(Path(self.cfg.exp_dir) / "output.log")
434
+ file_handler.setFormatter(formatter)
435
+ logger.addHandler(file_handler)
436
+
437
+ stream_handler = logging.StreamHandler()
438
+ stream_handler.setFormatter(formatter)
439
+ logger.addHandler(stream_handler)
440
+
441
+ # This is important to avoid duplicate log outputs
442
+ # See https://stackoverflow.com/questions/7173033/duplicate-log-output-when-using-python-logging-module # pylint:disable=line-too-long
443
+ logger.propagate = False
444
+
445
+ gatr.utils.logger.logging_initialized = True
446
+ logger.info("Hoi.")
447
+
448
+ def _initialize_mlflow(self):
449
+ """Initializes all things related to MLflow tracking."""
450
+
451
+ # Set up MLflow tracking location
452
+ Path(self.cfg.mlflow.db).parent.mkdir(exist_ok=True)
453
+ mlflow.set_tracking_uri(f"sqlite:///{Path(self.cfg.mlflow.db).resolve()}")
454
+
455
+ # Set up MLflow experiment
456
+ Path(self.cfg.mlflow.artifacts).mkdir(exist_ok=True)
457
+ try:
458
+ experiment_id = mlflow.create_experiment(
459
+ self.cfg.exp_name,
460
+ artifact_location=f"file:{Path(self.cfg.mlflow.artifacts).resolve()}",
461
+ )
462
+ logger.info(f"Created experiment {self.cfg.exp_name} with ID {experiment_id}")
463
+ except mlflow.exceptions.MlflowException:
464
+ pass # Experiment exists already
465
+
466
+ # Set MLflow experiment details
467
+ experiment = mlflow.set_experiment(self.cfg.exp_name)
468
+ experiment_id = experiment.experiment_id
469
+ artifact_loc = experiment.artifact_location
470
+
471
+ logger.info(
472
+ f"Set experiment {self.cfg.exp_name} with ID {experiment_id},"
473
+ f" artifact location {artifact_loc}"
474
+ )
475
+
476
+ return experiment_id
477
+
478
+ @staticmethod
479
+ def _silence_the_lambs():
480
+ """Silences other loggers."""
481
+ for name, other_logger in logging.root.manager.loggerDict.items():
482
+ if not "gatr_experiment" in name:
483
+ other_logger.level = logging.WARNING
484
+
485
+ @staticmethod
486
+ def _init_plt():
487
+ """Initializes matplotlib's rcparams to look good."""
488
+
489
+ sns.set_style("whitegrid")
490
+ matplotlib.rcParams.update(MATPLOTLIB_PARAMS)
491
+
492
+ def _save_config(self):
493
+ """Stores the config in the experiment folder and tracks it with mlflow."""
494
+
495
+ # Save config
496
+ config_filename = Path(self.cfg.exp_dir) / "config.yml"
497
+ logger.info(f"Saving config at {config_filename}")
498
+ with open(config_filename, "w", encoding="utf-8") as file:
499
+ file.write(OmegaConf.to_yaml(self.cfg))
500
+
501
+ # Store config as MLflow params
502
+ for key, value in flatten_dict(self.cfg).items():
503
+ log_mlflow(key, value, kind="param")
504
+
505
+ def _create_model(self):
506
+ """Creates the model from the config.
507
+
508
+ Returns
509
+ -------
510
+ model : torch.nn.Module
511
+ A randomly initialized model, following the specification in self.cfg.model
512
+ """
513
+
514
+ # Hydra magic!
515
+ return instantiate(self.cfg.model)
516
+
517
+ def _create_optimizer_and_scheduler(self):
518
+ """Creates optimizer and scheduler.
519
+
520
+ Returns
521
+ -------
522
+ optim : torch.optim.Optimizer
523
+ Adam optimizer for the parameters of self.model.
524
+ sched : torch.optim.lr_scheduler.LRScheduler
525
+ Exponential LR scheduler for optim.
526
+ """
527
+
528
+ optim = torch.optim.Adam(
529
+ self.model.parameters(),
530
+ lr=self.cfg.training.lr,
531
+ weight_decay=self.cfg.training.weight_decay,
532
+ )
533
+
534
+ num_scheduler_steps = self.cfg.training.steps // self.cfg.training.update_lr_every_n_steps
535
+ if num_scheduler_steps > 0:
536
+ gamma = self.cfg.training.lr_decay ** (1 / num_scheduler_steps)
537
+ else:
538
+ gamma = 1.0
539
+ scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=gamma)
540
+
541
+ return optim, scheduler
542
+
543
+ def _make_data_loader(self, dataset, batch_size, shuffle):
544
+ """Creates a data loader.
545
+
546
+ Parameters
547
+ ----------
548
+ dataset : torch.nn.utils.data.Dataset
549
+ Dataset.
550
+ batch_size : int
551
+ Batch size.
552
+ shuffle : bool
553
+ Whether the dataset is shuffled.
554
+
555
+ Returns
556
+ -------
557
+ dataloader
558
+ Data loader.
559
+ """
560
+ return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
561
+
562
+ def _prep_data(self, data, device=None):
563
+ """Data preparation during training loop, e.g. to move data to correct device and dtype."""
564
+ if isinstance(data, (tuple, list)):
565
+ data = tuple(x.to(device or self.device) for x in data)
566
+ elif isinstance(data, dict):
567
+ data = ({k: x.to(device or self.device) for k, x in data.items()},)
568
+ else:
569
+ data = (data.to(device or self.device),)
570
+
571
+ return data
572
+
573
+ def _step(self, data, step, val_data, val_loader):
574
+ """Everything that that may happen per step."""
575
+
576
+ # Move data to GPU, and other and other data prep stuff
577
+ data = self._prep_data(data)
578
+
579
+ # Forward pass
580
+ with torch.autocast(
581
+ device_type="cuda", dtype=self.dtype, enabled=self.cfg.training.float16
582
+ ):
583
+ ctx = torch.autograd.detect_anomaly if self.cfg.training.detect_anomaly else nullcontext
584
+ with ctx():
585
+ loss, metrics = self._forward(*data)
586
+
587
+ # Optimizer step
588
+ grad_norm = self._optimizer_step(loss)
589
+
590
+ # Post-step hooks: logging, validating, checkpoint saving, etc
591
+ self._post_step(loss, metrics, grad_norm, step, val_data, val_loader)
592
+
593
+ def _post_step(self, loss, metrics, grad_norm, step, val_data, val_loader):
594
+ # Log loss and metrics
595
+ self._log(loss, metrics, grad_norm, step)
596
+
597
+ # Debugging output
598
+ if step == 0:
599
+ logger.info(f"Finished first forward pass with loss {loss.item()}")
600
+
601
+ # Validation loop
602
+ if frequency_check(step, self.cfg.training.validate_every_n_steps, skip_initial=True):
603
+ logger.info(f"Starting validation at step {step}")
604
+ self.validate(val_loader, step)
605
+
606
+ # Plotting
607
+ if frequency_check(
608
+ step, self.cfg.training.plot_every_n_steps, include_fractional=(0.01, 0.1)
609
+ ):
610
+ self.visualize(val_data, step)
611
+
612
+ # Save model checkpoint
613
+ if frequency_check(step, self.cfg.training.save_model_every_n_steps, skip_initial=True):
614
+ self.save_model(f"model_step_{step}.pt")
615
+
616
+ # LR scheduler
617
+ if frequency_check(step, self.cfg.training.update_lr_every_n_steps, skip_initial=True):
618
+ self.scheduler.step()
619
+ logger.debug(f"Decaying LR to {self.scheduler.get_last_lr()[0]}")
620
+ log_mlflow("train.lr", self.scheduler.get_last_lr()[0], step=step)
621
+
622
+ # Custom hooks
623
+ for hook_step, hook_every_step, hook in self._hooks:
624
+ if hook_step == step or frequency_check(step, hook_every_step):
625
+ hook(model=self.model, step=step, experiment=self)
626
+
627
+ def _optimizer_step(self, loss):
628
+ """Optimizer step and gradient norm clipping."""
629
+
630
+ assert self.optim is not None
631
+ if not torch.isfinite(loss):
632
+ raise NaNError("NaN in loss!")
633
+
634
+ self.optim.zero_grad()
635
+ loss.backward()
636
+
637
+ # Grad norm clipping
638
+ try:
639
+ clip_norm = self.cfg.training.clip_grad_norm
640
+ grad_norm = torch.nn.utils.clip_grad_norm_(
641
+ self.model.parameters(), clip_norm, error_if_nonfinite=True
642
+ )
643
+ grad_norm = grad_norm.cpu().item()
644
+ except RuntimeError as e:
645
+ for n, p in self.model.named_parameters():
646
+ if not torch.isfinite(p.grad.flatten().norm()):
647
+ print(f"Non-finite grad in {n}")
648
+ raise e
649
+
650
+ self.optim.step()
651
+ if self.ema is not None:
652
+ self.ema.update()
653
+
654
+ return grad_norm
655
+
656
+ def _compute_metrics(self, dataloader):
657
+ """Given a dataloader, computes all relevant metrics. Can be adapted by subclasses.
658
+
659
+ Parameters
660
+ ----------
661
+ dataloader : torch.utils.data.DataLoader
662
+ Dataloader.
663
+
664
+ Returns
665
+ -------
666
+ metrics : dict with str keys and float values
667
+ Metrics computed from dataset.
668
+ """
669
+
670
+ # Move to eval mode and eval device
671
+ assert self.model is not None
672
+ self.model.eval()
673
+ eval_device = torch.device(self.cfg.training.eval_device)
674
+ self.model = self.model.to(eval_device)
675
+
676
+ aggregate_metrics: Dict[str, float] = defaultdict(float)
677
+
678
+ # Loop over dataset and compute error
679
+ for data in tqdm(dataloader, disable=False, desc="Evaluating"):
680
+ data = self._prep_data(data, device=eval_device)
681
+
682
+ # Forward pass
683
+ loss, metrics = self._forward(*data)
684
+
685
+ # Weight for this batch (last batches may be smaller)
686
+ batchsize = get_batchsize(data[0])
687
+ weight = batchsize / len(dataloader.dataset)
688
+
689
+ # Book-keeping
690
+ aggregate_metrics["loss"] += loss.item() * weight
691
+ for key, val in metrics.items():
692
+ aggregate_metrics[key] += val * weight
693
+
694
+ # Move model back to training mode and training device
695
+ self.model.train()
696
+ self.model = self.model.to(self.device)
697
+
698
+ # Return metrics
699
+ return aggregate_metrics
700
+
701
+ def _log(self, loss, metrics, grad_norm, step):
702
+ """Log to MLflow.
703
+
704
+ Parameters
705
+ ----------
706
+ loss : torch.Tensor
707
+ Loss
708
+ metrics : dict with str keys and float values
709
+ Additional metrics for logging
710
+ grad_norm : float
711
+ Gradient norm
712
+ """
713
+
714
+ if not frequency_check(step, self.cfg.training.log_every_n_steps):
715
+ return
716
+
717
+ metrics["loss"] = loss.item()
718
+ metrics["grad_norm"] = grad_norm
719
+ metrics["step"] = step
720
+ assert self._training_start_time is not None
721
+ metrics["time_total_s"] = time.time() - self._training_start_time
722
+ metrics["time_per_step_s"] = (time.time() - self._training_start_time) / (step + 1)
723
+
724
+ for key, values in metrics.items():
725
+ log_mlflow(f"train.{key}", values, step=step)
726
+
727
+ def _load_dataset(self, tag):
728
+ """Loads dataset. To be implemented by subclasses.
729
+
730
+ Parameters
731
+ ----------
732
+ tag : str
733
+ Dataset tag, like "train", "val", or one of self._eval_tags.
734
+
735
+ Returns
736
+ -------
737
+ dataset : torch.utils.data.Dataset
738
+ Dataset.
739
+ """
740
+ raise NotImplementedError
741
+
742
+ def _forward(self, *data):
743
+ """Model forward pass. To be implemented by subclasses.
744
+
745
+ Parameters
746
+ ----------
747
+ data : tuple of torch.Tensor
748
+ Data batch.
749
+
750
+ Returns
751
+ -------
752
+ loss : torch.Tensor
753
+ Loss
754
+ metrics : dict with str keys and float values
755
+ Additional metrics for logging
756
+ """
757
+ raise NotImplementedError
758
+
759
+ def visualize(self, dataset, step):
760
+ """Visualization function.
761
+
762
+ To be implemented by subclasses.
763
+ """
764
+
765
+ @property
766
+ def _eval_dataset_tags(self):
767
+ """Eval dataset tags, to be implemented by subclasses.
768
+
769
+ Returns
770
+ -------
771
+ tags : iterable of str
772
+ Eval dataset tags
773
+ """
774
+ return {"eval"}
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_wrapper.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+ from torch import nn
5
+
6
+
7
+ class BaseWrapper(nn.Module):
8
+ """Base GATr wrapper.
9
+
10
+ To be subclassed by experiment-specific wrapper classes.
11
+
12
+ Parameters
13
+ ----------
14
+ net : torch.nn.Module
15
+ GATr network.
16
+ scalars : bool
17
+ Whether the GATr model uses auxiliary scalars in its inputs and outputs. (In hidden
18
+ representations, GATr uses auxiliary scalars always.)
19
+ return_other : bool
20
+ Whether the wrapper should return regularization terms in addition to the model predictions.
21
+ """
22
+
23
+ def __init__(self, net, scalars=True, return_other=True):
24
+ super().__init__()
25
+ self.net = net
26
+ self.scalars = scalars
27
+ self.return_other = return_other
28
+
29
+ def build_attention_mask(
30
+ self, inputs, mv=None, s=None
31
+ ): # pylint: disable=unused-argument,redundant-returns-doc
32
+ """Construct attention mask.
33
+
34
+ Parameters
35
+ ----------
36
+ inputs : torch.Tensor
37
+ Raw inputs to wrapped network.
38
+ mv : torch.Tensor
39
+ Multivector embedding of inputs.
40
+ s : torch.Tensor
41
+ Auxiliary scalar embedding of inputs.
42
+
43
+ Returns
44
+ -------
45
+ attention_mask : None or torch.Tensor or xformers.ops.fmha.BlockDiagonalMask
46
+ Attention mask.
47
+ """
48
+ return None
49
+
50
+ def forward(self, inputs: torch.Tensor):
51
+ """Wrapped forward pass pass.
52
+
53
+ Parses inputs into GA + scalar representation, calls the forward pass of the wrapped net,
54
+ and extracts the outputs from the GA + scalar representation again.
55
+
56
+ Parameters
57
+ ----------
58
+ inputs : torch.Tensor
59
+ Raw inputs, as given by dataset.
60
+
61
+ Returns
62
+ -------
63
+ outputs : torch.Tensor
64
+ Raw outputs, as expected in dataset.
65
+ other : torch.Tensor
66
+ Additional output data, e.g. required for regularization. Only returned if
67
+ `self.return_other`.
68
+ """
69
+
70
+ multivector, scalars = self.embed_into_ga(inputs)
71
+ mask = self.build_attention_mask( # pylint: disable=assignment-from-none
72
+ inputs, mv=multivector, s=scalars
73
+ )
74
+ multivector_outputs, scalar_outputs = self.net(
75
+ multivector, scalars=scalars, attention_mask=mask
76
+ )
77
+ outputs, other = self.extract_from_ga(multivector_outputs, scalar_outputs)
78
+ outputs = self.postprocess_results(inputs, outputs)
79
+
80
+ if self.return_other:
81
+ return outputs, other
82
+
83
+ return outputs
84
+
85
+ def embed_into_ga(self, inputs):
86
+ """Embeds raw inputs into the geometric algebra (+ scalar) representation.
87
+
88
+ To be implemented by subclasses.
89
+
90
+ Parameters
91
+ ----------
92
+ inputs : torch.Tensor
93
+ Raw inputs, as given by dataset.
94
+
95
+ Returns
96
+ -------
97
+ mv_inputs : torch.Tensor
98
+ Multivector inputs, as expected by geometric network.
99
+ scalar_inputs : torch.Tensor or None
100
+ Scalar inputs, as expected by geometric network.
101
+ """
102
+ raise NotImplementedError
103
+
104
+ def extract_from_ga(self, multivector, scalars):
105
+ """Extracts raw outputs from the GATr multivector + scalar outputs.
106
+
107
+ To be implemented by subclasses.
108
+
109
+ Parameters
110
+ ----------
111
+ multivector : torch.Tensor
112
+ Multivector outputs from GATr.
113
+ scalars : torch.Tensor or None
114
+ Scalar outputs from GATr.
115
+
116
+ Returns
117
+ -------
118
+ outputs : torch.Tensor
119
+ Raw outputs, as expected in dataset.
120
+ other : torch.Tensor
121
+ Additional output data, e.g. required for regularization.
122
+ """
123
+ raise NotImplementedError
124
+
125
+ def postprocess_results(self, inputs, outputs): # pylint: disable=unused-argument
126
+ """Postprocesses the outputs extracted from the GA representation.
127
+
128
+ To be implemented by subclasses, optionally (by default, no postprocessing is applied).
129
+
130
+ Parameters
131
+ ----------
132
+ inputs
133
+ Raw inputs, pre embedding.
134
+ outputs : torch.Tensor
135
+ Raw outputs, pre postprocessing.
136
+
137
+ Returns
138
+ -------
139
+ processed_outputs : torch.Tensor
140
+ Raw outputs, after postprocessing.
141
+ """
142
+ return outputs
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .dataset import NBodyDataset
4
+ from .experiment import NBodyExperiment
5
+ from .simulator import NBodySimulator
6
+ from .wrappers import (
7
+ NBodyBaselineWrapper,
8
+ NBodyGATrWrapper,
9
+ NBodySE3TransformerWrapper,
10
+ NBodySEGNNWrapper,
11
+ )
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/dataset.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import numpy as np
4
+ import torch
5
+
6
+
7
+ class NBodyDataset(torch.utils.data.Dataset):
8
+ """N-body prediction dataset.
9
+
10
+ Loads data generated with generate_nbody_dataset.py from disk.
11
+
12
+ Parameters
13
+ ----------
14
+ filename : str or pathlib.Path
15
+ Path to the npz file with the dataset to be loaded.
16
+ subsample : None or float
17
+ If not None, defines the fraction of the dataset to be used. For instance, `subsample=0.1`
18
+ uses just 10% of the samples in the dataset.
19
+ keep_trajectories : bool
20
+ Whether to keep the full particle trajectories in the dataset. They are neither needed
21
+ for training nor evaluation, but can be useful for visualization.
22
+ """
23
+
24
+ def __init__(self, filename, subsample=None, keep_trajectories=False):
25
+ super().__init__()
26
+ self.x, self.y, self.trajectories = self._load_data(
27
+ filename, subsample, keep_trajectories=keep_trajectories
28
+ )
29
+
30
+ def __len__(self):
31
+ """Returns the number of samples in the dataset."""
32
+ return len(self.x)
33
+
34
+ def __getitem__(self, idx):
35
+ """Returns the `idx`-th sample from the dataset."""
36
+ return self.x[idx], self.y[idx]
37
+
38
+ @staticmethod
39
+ def _load_data(filename, subsample=None, keep_trajectories=False):
40
+ """Loads data from file and converts to input and output tensors."""
41
+ # Load data from file
42
+ npz = np.load(filename, "r")
43
+ m, x_initial, v_initial, x_final = (
44
+ npz["m"],
45
+ npz["x_initial"],
46
+ npz["v_initial"],
47
+ npz["x_final"],
48
+ )
49
+
50
+ # Convert to tensors
51
+ m = torch.from_numpy(m).to(torch.float32).unsqueeze(2)
52
+ x_initial = torch.from_numpy(x_initial).to(torch.float32)
53
+ v_initial = torch.from_numpy(v_initial).to(torch.float32)
54
+ x_final = torch.from_numpy(x_final).to(torch.float32)
55
+
56
+ # Concatenate into inputs and outputs
57
+ x = torch.cat((m, x_initial, v_initial), dim=2) # (batchsize, num_objects, 7)
58
+ y = x_final # (batchsize, num_objects, 3)
59
+
60
+ # Optionally, keep raw trajectories around (for plotting)
61
+ if keep_trajectories:
62
+ trajectories = npz["trajectories"]
63
+ else:
64
+ trajectories = None
65
+
66
+ # Subsample
67
+ if subsample is not None and subsample < 1.0:
68
+ n_original = len(x)
69
+ n_keep = int(round(subsample * n_original))
70
+ assert 0 < n_keep <= n_original
71
+ x = x[:n_keep]
72
+ y = y[:n_keep]
73
+ if trajectories is not None:
74
+ trajectories = trajectories[:n_keep]
75
+
76
+ return x, y, trajectories
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/experiment.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from pathlib import Path
4
+
5
+ import torch
6
+
7
+ from gatr.experiments.base_experiment import BaseExperiment
8
+ from gatr.experiments.nbody.dataset import NBodyDataset
9
+
10
+
11
+ class NBodyExperiment(BaseExperiment):
12
+ """Experiment manager for n-body prediction.
13
+
14
+ Parameters
15
+ ----------
16
+ cfg : OmegaConf
17
+ Experiment configuration. See the config folder in the repository for examples.
18
+ """
19
+
20
+ def __init__(self, cfg):
21
+ super().__init__(cfg)
22
+ self._mse_criterion = torch.nn.MSELoss()
23
+ self._mae_criterion = torch.nn.L1Loss(reduction="mean")
24
+
25
+ def _load_dataset(self, tag):
26
+ """Loads dataset.
27
+
28
+ Parameters
29
+ ----------
30
+ tag : str
31
+ Dataset tag, like "train", "val", or one of self._eval_tags.
32
+
33
+ Returns
34
+ -------
35
+ dataset : torch.utils.data.Dataset
36
+ Dataset.
37
+ """
38
+
39
+ if tag == "train":
40
+ subsample_fraction = self.cfg.data.subsample
41
+ else:
42
+ subsample_fraction = None
43
+
44
+ filename = Path(self.cfg.data.data_dir) / f"{tag}.npz"
45
+ keep_trajectories = tag == "val"
46
+ return NBodyDataset(
47
+ filename, subsample=subsample_fraction, keep_trajectories=keep_trajectories
48
+ )
49
+
50
+ def _forward(self, *data):
51
+ """Model forward pass.
52
+
53
+ Parameters
54
+ ----------
55
+ data : tuple of torch.Tensor
56
+ Data batch.
57
+
58
+ Returns
59
+ -------
60
+ loss : torch.Tensor
61
+ Loss
62
+ metrics : dict with str keys and float values
63
+ Additional metrics for logging
64
+ """
65
+
66
+ # Forward pass
67
+ assert self.model is not None
68
+ x, y = data
69
+ y_pred, reg = self.model(x)
70
+
71
+ # Compute loss
72
+ mse = self._mse_criterion(y_pred, y)
73
+ output_reg = torch.mean(reg)
74
+ loss = mse + self.cfg.training.output_regularization * output_reg
75
+
76
+ # Additional metrics
77
+ mae = self._mae_criterion(y_pred, y)
78
+ metrics = dict(
79
+ mse=mse.item(), rmse=loss.item() ** 0.5, output_reg=output_reg.item(), mae=mae.item()
80
+ )
81
+
82
+ return loss, metrics
83
+
84
+ @property
85
+ def _eval_dataset_tags(self):
86
+ """Eval dataset tags.
87
+
88
+ Returns
89
+ -------
90
+ tags : iterable of str
91
+ Eval dataset tags
92
+ """
93
+
94
+ # Only evaluate on object_generalization dataset when method supports variable token number
95
+ assert self.model is not None
96
+ if self.model.supports_variable_items:
97
+ return {"eval", "e3_generalization", "object_generalization"}
98
+
99
+ return {"eval", "e3_generalization"}
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/simulator.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import numpy as np
4
+ from scipy.stats import special_ortho_group
5
+
6
+ from gatr.utils.misc import sample_log_uniform, sample_uniform_in_circle
7
+
8
+
9
+ class NBodySimulator:
10
+ """Simulator for the n-body dataset.
11
+
12
+ Each sample consists of the positions of a n particicles (1 star and n - 1 planets), both before
13
+ and after the evolution of 100 time steps. The particle masses are also part of the sample.
14
+
15
+ The data is generated in the following way:
16
+ 1. The masses for the star and planets are sampled.
17
+ 2. The initial planet positions are sampled around the origin in the x-y plane. The star is at
18
+ (0, 0).
19
+ 3. The initial planet velocities are given by the velocity of a stable circular orbit, plus some
20
+ noise.
21
+ The star is initially at rest.
22
+ 4. The initial state is translated and rotated to an arbitrary position and orientation in
23
+ space.
24
+ 5. The final state is computed (using Newton's equations of gravity and Newton's method).
25
+ 6. To avoid annoying outliers, samples where the initial and final position of any object
26
+ are more than outlier_threshold are removed.
27
+
28
+ We use units where G = 1.
29
+
30
+ Parameters
31
+ ----------
32
+ time : float
33
+ Overall time period between initial and final state.
34
+ time_steps : int
35
+ Number of time steps that the time window is divided into for Euler integration.
36
+ star_mass_range : tuple of float
37
+ Minimum and maximum mass for the star.
38
+ planet_mass_range : tuple of float
39
+ Minimum and maximum mass for the planets.
40
+ radius_range : tuple of float
41
+ Minimum and maximum initial distance of the planets from the star.
42
+ vel_std : float
43
+ Noise scale for the initial planet velocity.
44
+ shift_std : float
45
+ Noise scale for the spatial translation.
46
+ ood_shift : float
47
+ Noise scale for the spatial translation for the translated sample.
48
+ outlier_threshold : float
49
+ Threshold for the rejection of outlier samples in which initial and final positions differ
50
+ substantially.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ time=0.1,
56
+ time_steps=100,
57
+ star_mass_range=(1.0, 10.0),
58
+ planet_mass_range=(0.01, 0.1),
59
+ radius_range=(0.1, 1.0),
60
+ vel_std=0.01,
61
+ shift_std=20.0,
62
+ ood_shift=200.0,
63
+ outlier_threshold=2.0,
64
+ ):
65
+ self.time = time
66
+ self.delta_t = time / time_steps
67
+ self.time_steps = time_steps
68
+ self.star_mass_range = star_mass_range
69
+ self.planet_mass_range = planet_mass_range
70
+ self.radius_range = radius_range
71
+ self.vel_std = vel_std
72
+ self.shift_std = shift_std
73
+ self.ood_shift = ood_shift
74
+ self.outlier_threshold = outlier_threshold
75
+
76
+ def sample(self, num_samples, num_planets=5, domain_shift=False):
77
+ """Samples from gravity problem.
78
+
79
+ Parameters
80
+ ----------
81
+ num_samples : int
82
+ Number of samples.
83
+ num_planets : int
84
+ Number of planets in the dataset (as there is always a single star, we have
85
+ `n = num_planets + 1`).
86
+ domain_shift : bool
87
+ Whether to sample with larger spatial translation to generate domain-shifted data.
88
+ """
89
+
90
+ # Sample a bit more initially, to make up for outlier removal later
91
+ num_candidates = int(round(1.1 * num_samples))
92
+
93
+ # 1. Sample planet masses
94
+ star_mass = sample_log_uniform(*self.star_mass_range, size=(num_candidates, 1))
95
+ planet_masses = sample_log_uniform(
96
+ *self.planet_mass_range, size=(num_candidates, num_planets)
97
+ )
98
+ masses = np.concatenate((star_mass, planet_masses), axis=1)
99
+
100
+ # 2. Sample initial positions in x-y plane around origin
101
+ planet_pos = np.zeros((num_candidates, num_planets, 3))
102
+ planet_pos[..., :2] = sample_uniform_in_circle(
103
+ num_candidates * num_planets,
104
+ min_radius=self.radius_range[0],
105
+ max_radius=self.radius_range[1],
106
+ ).reshape((num_candidates, num_planets, 2))
107
+ x_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_pos), axis=1)
108
+
109
+ # 3. Sample initial velocities, approximately as stable circular orbits
110
+ planet_vel = self._sample_planet_velocities(star_mass, planet_pos)
111
+ v_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_vel), axis=1)
112
+
113
+ # 4. Translate, rotate, permute
114
+ masses, x_initial, v_initial = self._shift_and_rotate(
115
+ masses, x_initial, v_initial, domain_shift=domain_shift
116
+ )
117
+
118
+ # 5. Evolve Newtonian gravity
119
+ x_final, trajectory = self._simulate(masses, x_initial, v_initial)
120
+
121
+ # 6. Remove outliers
122
+ max_distance = np.max(np.linalg.norm(x_final - x_initial, axis=-1), axis=-1)
123
+ mask = max_distance <= self.outlier_threshold
124
+ masses, x_initial, v_initial, x_final, trajectory = (
125
+ masses[mask],
126
+ x_initial[mask],
127
+ v_initial[mask],
128
+ x_final[mask],
129
+ trajectory[mask],
130
+ )
131
+
132
+ # Cut down to requested number
133
+ masses, x_initial, v_initial, x_final, trajectory = (
134
+ masses[:num_samples],
135
+ x_initial[:num_samples],
136
+ v_initial[:num_samples],
137
+ x_final[:num_samples],
138
+ trajectory[:num_samples],
139
+ )
140
+
141
+ return masses, x_initial, v_initial, x_final, trajectory
142
+
143
+ def _sample_planet_velocities(self, star_mass, x):
144
+ """Samples planet velocities around those that give stable circular orbits."""
145
+
146
+ batchsize, num_planets, _ = x.shape
147
+
148
+ # Defines rotation plane. Clockwise or counterclockwise is random for each planet.
149
+ orientation = np.zeros((batchsize, num_planets, 3))
150
+ orientation[:, :, 2] = np.random.choice(
151
+ a=[-1.0, 1.0], size=(batchsize, num_planets), p=[0.5, 0.5]
152
+ )
153
+
154
+ # Compute stable velocities
155
+ star_mass = star_mass[:, :, np.newaxis] # (batchsize, 1, 1)
156
+ radii = np.linalg.norm(x, axis=-1)[:, :, np.newaxis] # (batchsize, num_planets, 1)
157
+ v_stable = np.cross(orientation, x) * star_mass**0.5 / radii**1.5
158
+
159
+ # Add noise
160
+ v = v_stable + np.random.normal(scale=self.vel_std, size=(batchsize, num_planets, 3))
161
+
162
+ return v
163
+
164
+ def _shift_and_rotate(self, m, x, v, domain_shift=False):
165
+ """Performs random E(3) transformations and permutations on given positions / velocities."""
166
+
167
+ batchsize, num_objects, _ = x.shape
168
+
169
+ # Permutations over objects
170
+ for i in range(batchsize):
171
+ perm = np.random.permutation(num_objects)
172
+ m[i] = m[i][perm]
173
+ x[i] = x[i][perm, :]
174
+ v[i] = v[i][perm, :]
175
+
176
+ # Rotations from Haar measure
177
+ rotations = special_ortho_group(3).rvs(size=batchsize).reshape(batchsize, 1, 3, 3)
178
+ x = np.einsum("bnij,bnj->bni", rotations, x)
179
+ v = np.einsum("bnij,bnj->bni", rotations, v)
180
+
181
+ # Translations
182
+ shifts = np.random.normal(scale=self.shift_std, size=(batchsize, 1, 3))
183
+ x = x + shifts
184
+
185
+ # OOD shift
186
+ if domain_shift:
187
+ shifts = np.array([self.ood_shift, 0, 0]).reshape((1, 1, 3))
188
+ x = x + shifts
189
+
190
+ return m, x, v
191
+
192
+ def _simulate(self, m, x_initial, v_initial):
193
+ """Evolves an initial state under Newtonian equations of motions."""
194
+
195
+ x, v = x_initial, v_initial
196
+ trajectory = [x_initial]
197
+
198
+ for _ in range(self.time_steps):
199
+ a = self._compute_accelerations(m, x)
200
+ v = v + self.delta_t * a
201
+ x = x + self.delta_t * v
202
+ trajectory.append(x)
203
+
204
+ return x, np.array(trajectory).transpose([1, 2, 0, 3])
205
+
206
+ @staticmethod
207
+ def _compute_accelerations(m, x):
208
+ """Computes accelerations for a set of point masses according to Newtonian gravity."""
209
+ batchsize, num_objects, _ = x.shape
210
+ mm = m.reshape((batchsize, 1, num_objects, 1)) * m.reshape(
211
+ (batchsize, num_objects, 1, 1)
212
+ ) # (b, n, n, 1)
213
+
214
+ distance_vectors = x.reshape((batchsize, 1, num_objects, 3)) - x.reshape(
215
+ (batchsize, num_objects, 1, 3)
216
+ ) # (b, n, n, 3)
217
+ distances = np.linalg.norm(distance_vectors, axis=-1)[:, :, :, np.newaxis] # (b, n, n, 1)
218
+ distances[np.abs(distances) < 1e-9] = 1.0
219
+
220
+ forces = distance_vectors * mm / distances**3 # (b, n, n, 3)
221
+ accelerations = np.sum(forces, axis=2) / m.reshape(batchsize, num_objects, 1) # (b, n, 3)
222
+
223
+ return accelerations # (b, n, 3)
gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/wrappers.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import dgl
4
+ import numpy as np
5
+ import torch
6
+ from e3nn.o3 import Irreps, spherical_harmonics
7
+ from torch import nn
8
+ from torch_geometric.data import Data
9
+ from torch_geometric.nn import knn_graph
10
+ from torch_scatter import scatter
11
+
12
+ from gatr.baselines.gcan import GCAGNN
13
+ from gatr.baselines.transformer import BaselineAxialTransformer, BaselineTransformer
14
+ from gatr.experiments.base_wrapper import BaseWrapper
15
+ from gatr.interface import (
16
+ embed_point,
17
+ embed_scalar,
18
+ embed_translation,
19
+ extract_point,
20
+ extract_point_embedding_reg,
21
+ )
22
+ from gatr.utils.misc import make_full_edge_index
23
+
24
+
25
+ def embed_nbody_data_in_pga(inputs):
26
+ """Represent the n-body initial state in PGA multivectors.
27
+
28
+ Masses are represented as scalars, positions as trivectors, and velocities as bivectors
29
+ (like translations). All three are summed (this is equivalent to concatenation, as an equi
30
+ linear layer can easily separate the grades again).
31
+
32
+ This function is used both by the GATr and by the GCAN wrappers.
33
+
34
+ Parameters
35
+ ----------
36
+ inputs : torch.Tensor with shape (batchsize, objects, 7)
37
+ n-body initial state: a concatenation of masses, initial positions, and initial
38
+ velocities along the feature dimension.
39
+
40
+ Returns
41
+ -------
42
+ multivector : torch.Tensor with shape (batchsize, objects, 1, 16)
43
+ GA embedding.
44
+ """
45
+
46
+ # Build one multivector holding masses, points, and velocities for each object
47
+ masses = inputs[:, :, [0]] # (batchsize, objects, 1)
48
+ masses = embed_scalar(masses) # (batchsize, objects, 16)
49
+ points = inputs[:, :, 1:4] # (batchsize, objects, 3)
50
+ points = embed_point(points) # (batchsize, objects, 16)
51
+ velocities = inputs[:, :, 4:7] # (batchsize, objects, 3)
52
+ velocities = embed_translation(velocities) # (batchsize, objects, 16)
53
+ multivector = masses + points + velocities # (batchsize, objects, 16)
54
+
55
+ # Insert channel dimension
56
+ multivector = multivector.unsqueeze(2) # (batchsize, objects, 1, 16)
57
+
58
+ return multivector
59
+
60
+
61
+ class NBodyGATrWrapper(BaseWrapper):
62
+ """Wraps around GATr for the n-body prediction experiment.
63
+
64
+ Parameters
65
+ ----------
66
+ net : torch.nn.Module
67
+ GATr model that accepts inputs with 1 multivector channel and 1 scalar channel, and
68
+ returns outputs with 1 multivector channel and 1 scalar channel.
69
+ """
70
+
71
+ def __init__(self, net):
72
+ super().__init__(net, scalars=True, return_other=True)
73
+ self.supports_variable_items = True
74
+
75
+ def embed_into_ga(self, inputs):
76
+ """Embeds raw inputs into the geometric algebra (+ scalar) representation.
77
+
78
+ Parameters
79
+ ----------
80
+ inputs : torch.Tensor with shape (batchsize, objects, 7)
81
+ n-body initial state: a concatenation of masses, initial positions, and initial
82
+ velocities along the feature dimension.
83
+
84
+ Returns
85
+ -------
86
+ mv_inputs : torch.Tensor
87
+ Multivector representation of masses, positions, and velocities.
88
+ scalar_inputs : torch.Tensor or None
89
+ Dummy auxiliary scalars, containing no information.
90
+ """
91
+ batchsize, num_objects, _ = inputs.shape
92
+
93
+ # Build one multivector holding masses, positions, and velocities for each object
94
+ multivector = embed_nbody_data_in_pga(inputs)
95
+
96
+ # Scalar inputs are not really needed here
97
+ scalars = torch.zeros((batchsize, num_objects, 1), device=inputs.device)
98
+
99
+ return multivector, scalars
100
+
101
+ def extract_from_ga(self, multivector, scalars):
102
+ """Extracts raw outputs from the GATr multivector + scalar outputs.
103
+
104
+ We parameterize the predicted final positions as points.
105
+
106
+ Parameters
107
+ ----------
108
+ multivector : torch.Tensor
109
+ Multivector outputs from GATr.
110
+ scalars : torch.Tensor or None
111
+ Scalar outputs from GATr.
112
+
113
+ Returns
114
+ -------
115
+ outputs : torch.Tensor
116
+ Predicted final-state positions.
117
+ other : torch.Tensor
118
+ Regularization terms.
119
+ """
120
+
121
+ # Check channels of inputs. Batchsize and object numbers are free.
122
+ assert multivector.shape[2:] == (1, 16)
123
+ assert scalars.shape[2:] == (1,)
124
+
125
+ # Extract position
126
+ points = extract_point(multivector[:, :, 0, :])
127
+
128
+ # Extract non-point components and compute regularization
129
+ other = extract_point_embedding_reg(multivector[:, :, 0, :])
130
+ reg = torch.sum(other**2, dim=[1, 2])
131
+ if self.scalars:
132
+ reg = reg + torch.sum(scalars**2, dim=[1, 2])
133
+
134
+ return points, reg
135
+
136
+
137
+ class NBodyBaselineWrapper(nn.Module):
138
+ """Wraps around simple baselines (MLP or Transformer) for the n-body prediction experiment.
139
+
140
+ Parameters
141
+ ----------
142
+ net : torch.nn.Module
143
+ Model that accepts inputs with 7 channels and returns outputs with 3 channels.
144
+ """
145
+
146
+ def __init__(self, net):
147
+ super().__init__()
148
+ self.net = net
149
+ self.supports_variable_items = isinstance(
150
+ net, (BaselineTransformer, BaselineAxialTransformer)
151
+ )
152
+
153
+ def forward(self, inputs):
154
+ """Wrapped forward pass.
155
+
156
+ Parameters
157
+ ----------
158
+ inputs : torch.Tensor
159
+ Raw inputs, as given by dataset.
160
+
161
+ Returns
162
+ -------
163
+ outputs : torch.Tensor
164
+ Raw outputs, as expected in dataset.
165
+ other : torch.Tensor
166
+ Dummy term, since the baselines do not require regularization.
167
+ """
168
+ batchsize = inputs.shape[0]
169
+ return self.net(inputs), torch.zeros(batchsize, device=inputs.device)
170
+
171
+
172
+ class NBodySEGNNWrapper(nn.Module):
173
+ """Wraps around the SEGNN baseline for the n-body prediction experiment.
174
+
175
+ Parameters
176
+ ----------
177
+ net : torch.nn.Module
178
+ SEGNN model that accepts inputs with inputs with 2 vector channels and 1 scalar channel,
179
+ and returns outputs with 1 vector channel.
180
+ """
181
+
182
+ def __init__(self, net, neighbors, lmax_attr, canonicalize_mode="com"):
183
+ super().__init__()
184
+
185
+ self.net = net
186
+
187
+ self.canonicalize_mode = canonicalize_mode
188
+ self.neighbors = neighbors
189
+ self.transform_attr_irreps = Irreps.spherical_harmonics(lmax_attr)
190
+ self.supports_variable_items = True
191
+
192
+ def forward(self, inputs):
193
+ """Wrapped forward pass.
194
+
195
+ Parameters
196
+ ----------
197
+ inputs : torch.Tensor
198
+ Raw inputs, as given by dataset.
199
+
200
+ Returns
201
+ -------
202
+ outputs : torch.Tensor
203
+ Raw outputs, as expected in dataset.
204
+ other : torch.Tensor
205
+ Dummy term, since the baselines do not require regularization.
206
+
207
+ Raises
208
+ ------
209
+ ValueError
210
+ If `self.canonicalize_mode` is invalid.
211
+ """
212
+ batchsize, num_objects, _ = inputs.shape
213
+
214
+ # Separate into scalars and vectors
215
+ masses = inputs[:, :, [0]] # (batchsize, objects, 1)
216
+ locations = inputs[:, :, 1:4] # (batchsize, objects, 3)
217
+ velocities = inputs[:, :, 4:7] # (batchsize, objects, 3)
218
+
219
+ # Canonicalize
220
+ if self.canonicalize_mode == "com":
221
+ weights = masses
222
+ elif self.canonicalize_mode == "heaviest":
223
+ weights = torch.exp(2.0 * masses.double())
224
+ elif self.canonicalize_mode == "even":
225
+ weights = torch.ones_like(masses)
226
+ else:
227
+ raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}")
228
+
229
+ com = torch.sum(
230
+ weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(),
231
+ dim=-2,
232
+ keepdim=True,
233
+ ).float()
234
+ locations = locations - com
235
+
236
+ # Represent as graph
237
+ graph = Data(pos=locations.view(-1, 3), vel=velocities.view(-1, 3), mass=masses.view(-1, 1))
238
+ batch = torch.arange(0, batchsize, device=inputs.device)
239
+ graph.batch = batch.repeat_interleave(num_objects).to(inputs.device, torch.long)
240
+ graph.edge_index = knn_graph(locations.view(-1, 3), self.neighbors, graph.batch)
241
+
242
+ graph = self._augment_gravity_graph(graph) # Add O3 attributes
243
+
244
+ # Push through model
245
+ pred_shift = self.net(graph)
246
+ pred_shift = pred_shift.view(batchsize, num_objects, 3)
247
+ predictions = (
248
+ locations + pred_shift
249
+ ) # The model predicts the shift, not the final positions
250
+
251
+ # Undo canonicalization
252
+ predictions = predictions + com
253
+
254
+ return predictions, torch.zeros(batchsize, device=inputs.device)
255
+
256
+ def _augment_gravity_graph(self, graph):
257
+ """SEGNN feature engineering for n-body experiments.
258
+
259
+ Constructs node features (position relative to mean position, velocity embedding, absolute
260
+ velocity) and edge features (pairwise distances, product of charges / masses).
261
+ """
262
+
263
+ pos = graph.pos
264
+ vel = graph.vel
265
+ mass = graph.mass
266
+
267
+ prod_mass = mass[graph.edge_index[0]] * mass[graph.edge_index[1]]
268
+ rel_pos = pos[graph.edge_index[0]] - pos[graph.edge_index[1]]
269
+ edge_dist = torch.sqrt(rel_pos.pow(2).sum(1, keepdims=True))
270
+
271
+ graph.edge_attr = spherical_harmonics(
272
+ self.transform_attr_irreps, rel_pos, normalize=True, normalization="integral"
273
+ )
274
+ vel_embedding = spherical_harmonics(
275
+ self.transform_attr_irreps, vel, normalize=True, normalization="integral"
276
+ )
277
+ graph.node_attr = (
278
+ scatter(graph.edge_attr, graph.edge_index[1], dim=0, reduce="mean") + vel_embedding
279
+ )
280
+
281
+ vel_abs = torch.sqrt(vel.pow(2).sum(1, keepdims=True))
282
+
283
+ graph.x = torch.cat((pos, vel, vel_abs), 1) # Note that pos is here already canonicalized
284
+ graph.additional_message_features = torch.cat((edge_dist, prod_mass), dim=-1)
285
+ return graph
286
+
287
+
288
+ class NBodySE3TransformerWrapper(nn.Module):
289
+ """Wraps around the SE3-Transformer baseline for the n-body prediction experiment.
290
+
291
+ Parameters
292
+ ----------
293
+ net : torch.nn.Module
294
+ SE3-Transformer model.
295
+ """
296
+
297
+ def __init__(self, net, canonicalize_to_com=True, canonicalize_mode="com"):
298
+ super().__init__()
299
+
300
+ self.net = net
301
+ self.canonicalize_to_com = canonicalize_to_com
302
+ self.canonicalize_mode = canonicalize_mode
303
+ self.supports_variable_items = True
304
+
305
+ def forward(self, inputs):
306
+ """Wrapped forward pass.
307
+
308
+ Parameters
309
+ ----------
310
+ inputs : torch.Tensor
311
+ Raw inputs, as given by dataset.
312
+
313
+ Returns
314
+ -------
315
+ outputs : torch.Tensor
316
+ Raw outputs, as expected in dataset.
317
+ other : torch.Tensor
318
+ Dummy term, since the baselines do not require regularization.
319
+
320
+ Raises
321
+ ------
322
+ ValueError
323
+ If `self.canonicalize_mode` is invalid.
324
+ """
325
+ batchsize, num_objects, _ = inputs.shape
326
+
327
+ # Separate into scalars and vectors
328
+ masses = inputs[:, :, [0]] # (batchsize, objects, 1)
329
+ locations = inputs[:, :, 1:4] # (batchsize, objects, 3)
330
+ velocities = inputs[:, :, 4:7] # (batchsize, objects, 3)
331
+
332
+ # Canonicalize to center-of-mass frame if requested
333
+ if self.canonicalize_to_com:
334
+ if self.canonicalize_mode == "com":
335
+ weights = masses
336
+ elif self.canonicalize_mode == "heaviest":
337
+ weights = torch.exp(2.0 * masses.double())
338
+ else:
339
+ raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}")
340
+ com = torch.sum(
341
+ weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(),
342
+ dim=-2,
343
+ keepdim=True,
344
+ ).float()
345
+ locations = locations - com
346
+ else:
347
+ com = torch.zeros_like(locations)
348
+
349
+ # Represent as graph
350
+ graphs = self._build_graphs(locations, velocities, masses)
351
+
352
+ # Push through model
353
+ predictions = self.net(graphs)
354
+ predictions = predictions[:, 0, :] # Only positions, not velocities
355
+ predictions = predictions.view(batchsize, num_objects, 3)
356
+ predictions = (
357
+ locations + predictions
358
+ ) # Model predicts positions relative to initial pos, make it absolute
359
+
360
+ # Undo canonicalization
361
+ if self.canonicalize_to_com:
362
+ predictions = predictions + com
363
+
364
+ return predictions, torch.zeros(batchsize, device=inputs.device)
365
+
366
+ def _build_graphs(self, locations, velocities, masses):
367
+ """Builds graph for a full batch."""
368
+ graphs = [
369
+ self._build_graph(loc, vel, m) for loc, vel, m in zip(locations, velocities, masses)
370
+ ]
371
+ graphs = dgl.batch(graphs)
372
+
373
+ return graphs
374
+
375
+ def _build_graph(self, locations, velocities, masses):
376
+ """Builds graph for a single sample."""
377
+ n_points = len(locations)
378
+ indices_src, indices_dst = self._fully_connected_idx(n_points)
379
+ graph = dgl.DGLGraph((indices_src, indices_dst)).to(locations.device)
380
+ graph.ndata["x"] = torch.unsqueeze(locations, dim=1) # [N, 1, 3]
381
+ graph.ndata["v"] = torch.unsqueeze(velocities, dim=1) # [N, 1, 3]
382
+ graph.ndata["c"] = torch.unsqueeze(masses, dim=1) # [N, 1, 1]
383
+ graph.edata["d"] = locations[indices_dst] - locations[indices_src] # relative postions
384
+ graph.edata["w"] = masses[indices_dst] * masses[indices_src]
385
+ return graph
386
+
387
+ @staticmethod
388
+ def _fully_connected_idx(num_atoms):
389
+ """Creates source and destination indices for a fully connected graph."""
390
+ src = []
391
+ dst = []
392
+ for i in range(num_atoms):
393
+ for j in range(num_atoms):
394
+ if i != j:
395
+ src.append(i)
396
+ dst.append(j)
397
+ return np.array(src), np.array(dst)
398
+
399
+
400
+ class NBodyGCANWrapper(nn.Module):
401
+ """Wraps around GCA-MLP and GCA-GNN baselines for the n-body experiment.
402
+
403
+ Parameters
404
+ ----------
405
+ net : torch.nn.Module
406
+ GCAN model that accepts inputs with multivector inputs with 1 channel and
407
+ returns multivector outputs with 1 channel.
408
+ """
409
+
410
+ def __init__(self, net, geometric_batching=False):
411
+ super().__init__()
412
+ self.net = net
413
+ self._geometric_batching = geometric_batching
414
+ self.supports_variable_items = isinstance(net, GCAGNN)
415
+
416
+ def forward(self, inputs: torch.Tensor):
417
+ """Wrapped forward pass.
418
+
419
+ Parameters
420
+ ----------
421
+ inputs : torch.Tensor
422
+ Raw inputs, as given by dataset.
423
+
424
+ Returns
425
+ -------
426
+ outputs : torch.Tensor
427
+ Raw outputs, as expected in dataset.
428
+ other : torch.Tensor
429
+ Dummy term, since the baselines do not require regularization.
430
+ """
431
+
432
+ multivector = embed_nbody_data_in_pga(inputs)
433
+
434
+ if self._geometric_batching:
435
+ # PyG-style batching, with a single batch-token dimension and edge list
436
+ edge_index = self.make_edge_index(inputs)
437
+ multivector = multivector.view(-1, *multivector.shape[2:])
438
+ multivector_outputs = self.net(multivector, edge_index=edge_index)
439
+ multivector_outputs = multivector_outputs.view(
440
+ inputs.shape[0], -1, *multivector_outputs.shape[1:]
441
+ )
442
+ else:
443
+ # Standard batching, with (batch, token, ...) tensors
444
+ multivector_outputs = self.net(multivector)
445
+
446
+ outputs, reg = self.extract_from_ga(multivector_outputs)
447
+ return outputs, reg
448
+
449
+ @staticmethod
450
+ def extract_from_ga(multivector):
451
+ """Extracts predicted positions from PGA multivectors."""
452
+ # Check channels of inputs. Batchsize and object numbers are free.
453
+ assert multivector.shape[2:] == (1, 16)
454
+
455
+ # Extract position
456
+ points = extract_point(multivector[:, :, 0, :])
457
+
458
+ # Extract non-point components and compute regularization
459
+ other = extract_point_embedding_reg(multivector[:, :, 0, :])
460
+ reg = torch.sum(other**2, dim=[1, 2])
461
+ return points, reg
462
+
463
+ @staticmethod
464
+ def make_edge_index(inputs):
465
+ """Constructs an edge index for fully connected graph."""
466
+ batchsize, num_items, _ = inputs.shape
467
+ return make_full_edge_index(
468
+ num_items, batchsize=batchsize, self_loops=False, device=inputs.device
469
+ )
470
+
471
+ def to(self, *args, **kwargs):
472
+ """Send to device.
473
+
474
+ Overwritten to also move the CliffordAlgebra object, which is not an nn.Module.
475
+ """
476
+ resursively_move_gcan_pga(self, *args, **kwargs)
477
+ super().to(*args, **kwargs)
478
+ return self
479
+
480
+
481
+ def resursively_move_gcan_pga(net, *args, **kwargs):
482
+ """Moves all PGA instances in GCAN component to device / dtype."""
483
+ try:
484
+ net.pga.to(*args, **kwargs)
485
+ except AttributeError:
486
+ pass
487
+
488
+ for child in net.children():
489
+ resursively_move_gcan_pga(child, *args, **kwargs)
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .object import (
4
+ embed_3d_object,
5
+ embed_3d_object_two_vec,
6
+ extract_3d_object,
7
+ extract_3d_object_two_vec,
8
+ )
9
+ from .plane import embed_oriented_plane, extract_oriented_plane
10
+ from .point import embed_point, extract_point, extract_point_embedding_reg
11
+ from .pseudoscalar import embed_pseudoscalar, extract_pseudoscalar
12
+ from .reflection import embed_reflection, extract_reflection
13
+ from .rotation import embed_rotation, extract_rotation
14
+ from .scalar import embed_scalar, extract_scalar
15
+ from .translation import embed_translation, extract_translation
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/object.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+ from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane
8
+ from gatr.interface.point import embed_point, extract_point
9
+ from gatr.interface.rotation import embed_rotation, extract_rotation
10
+ from gatr.interface.translation import embed_translation
11
+ from gatr.primitives.bilinear import geometric_product, outer_product
12
+ from gatr.primitives.linear import reverse
13
+
14
+
15
+ def embed_3d_object(
16
+ position: torch.Tensor, orientation: torch.Tensor, explicit_point: bool = False
17
+ ) -> torch.Tensor:
18
+ """Embeds the pose of a 3D object PGA multivectors.
19
+
20
+ The pose is given by a position and a orientation quaternion. The latter is assumed to follow
21
+ the pybullet conventions: to be given in Hamilton convention, where ijk = -1, and with the
22
+ scalar component last (ijkw order).
23
+
24
+ The embedding contains three plane multivectors v_i with
25
+ ```
26
+ v_i = T(p) R(q) e_i reverse(T(p) R(q))
27
+ ```
28
+ where `T()` is the translation embedding, `R()` is the rotation embedding, and `e_i` are the PGA
29
+ basis vectors.
30
+
31
+ If `explicit_point`, then a fourth multivector represents the position itself.
32
+
33
+ References
34
+ ----------
35
+ Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478
36
+
37
+ Parameters
38
+ ----------
39
+ position : torch.Tensor with shape (..., 1, 3)
40
+ Position in 3D space.
41
+ orientation : torch.Tensor with shape (..., 1, 4)
42
+ Quaternions in ijkw order and Hamilton convention (ijk=-1)
43
+ explicit_point : bool
44
+ If True, in addition to the three planes we provide the explicit point representation
45
+ `P(p)`.
46
+
47
+ Returns
48
+ -------
49
+ multivector : torch.Tensor with shape (..., n_channels, 16)
50
+ Embedding into multivectors, with `n_channels = 4 if explicit_point else 3`.
51
+ """
52
+
53
+ # Check inputs
54
+ assert position.shape[-2:] == (1, 3)
55
+ assert orientation.shape[-2:] == (1, 4)
56
+
57
+ # Basis planes
58
+ basis = torch.zeros(3, 16, dtype=position.dtype, device=position.device) # (3, 16)
59
+ basis[:, 2:5] = torch.eye(
60
+ 3, dtype=position.dtype, device=position.device
61
+ ) # basis[i] has e_i = 1
62
+
63
+ # Translation and rotation
64
+ t = embed_translation(position) # (..., 1, 16)
65
+ r = embed_rotation(orientation) # (..., 1, 16)
66
+ tr = geometric_product(t, r) # (..., 1, 16)
67
+
68
+ # Construct embedding
69
+ embedding = geometric_product(geometric_product(tr, basis), reverse(tr)) # (..., 3, 16)
70
+
71
+ # Optional point embedding
72
+ if explicit_point:
73
+ point = embed_point(position)
74
+ embedding = torch.cat((embedding, point), dim=-2) # (..., 4, 16)
75
+
76
+ return embedding
77
+
78
+
79
+ def extract_3d_object(
80
+ multivector: torch.Tensor,
81
+ normalize_quaternion: bool = True,
82
+ sign_reference: Optional[torch.Tensor] = None,
83
+ ) -> torch.Tensor:
84
+ """Extracts 3D position and quaternion orientation from the multivector embedding of an object.
85
+
86
+ This function inverts embed_3d_object().
87
+
88
+ The extraction starts from three (plane) MVs v_i and is based on the magic equation
89
+ ```
90
+ P(p) = v_1 ^ v_2 ^ v_3
91
+ q = (1 + sum_i <v_i>_E e_i)
92
+ ```
93
+ where `<v_i>_E` is the projection of v_i to the Euclidean vector components.
94
+
95
+ Parameters
96
+ ----------
97
+ multivector : torch.Tensor with shape (..., 3 or 4, 16)
98
+ Object embedding.
99
+ normalize_quaternion : bool
100
+ Whether to normalize quaternions.
101
+ sign_reference : None or torch.Tensor
102
+ If provided, used to fix the (ambiguous) sign of the orientation quaternion.
103
+
104
+ Returns
105
+ -------
106
+ position : torch.Tensor with shape (..., 1, 3)
107
+ Position in 3D space.
108
+ orientation : torch.Tensor with shape (..., 1, 4)
109
+ Quaternions in ijkw order and Hamilton convention (ijk=-1).
110
+ """
111
+
112
+ # Split inputs
113
+ v = [multivector[..., [i], :] for i in range(3)] # (..., 1, 16) each
114
+
115
+ # Basis vectors
116
+ basis = torch.zeros(3, 16, dtype=multivector.dtype, device=multivector.device) # (3, 16)
117
+ basis[:, 2:5] = torch.eye(
118
+ 3, dtype=multivector.dtype, device=multivector.device
119
+ ) # basis[i] has e_i = 1
120
+ projection = torch.sum(basis, dim=0) # (16)
121
+
122
+ # Extract position
123
+ if multivector.shape[-2] == 4:
124
+ position = extract_point(multivector[..., [3], :]) # (..., 1, 3)
125
+ else:
126
+ position = outer_product(outer_product(v[0], v[1]), v[2]) # (..., 1, 16)
127
+ position = extract_point(position) # (..., 1, 3)
128
+
129
+ # Extract orientation
130
+ orientation = torch.zeros(16, dtype=multivector.dtype, device=multivector.device)
131
+ orientation[0] = 1.0
132
+ for vi, ei in zip(v, basis):
133
+ vi_proj = projection * vi # Project to Euclidean vector components
134
+ orientation = orientation + geometric_product(vi_proj, ei) # Magic equation
135
+
136
+ quat = extract_rotation(orientation, normalize=normalize_quaternion)
137
+
138
+ # Fix quaternion sign
139
+ if sign_reference is not None:
140
+ sign = torch.sign(torch.sum(sign_reference * quat, dim=-1, keepdim=True))
141
+ quat = sign * quat
142
+
143
+ return position, quat
144
+
145
+
146
+ def embed_3d_object_two_vec(position: torch.Tensor, orientation: torch.Tensor) -> torch.Tensor:
147
+ """Embeds the pose of a 3D object in two-vec parameterization into the PGA.
148
+
149
+ The inputs consist of the position of an object and two vectors that specify its orientation.
150
+ These two vectors can be generated from a rotation matrix by taking the first two column
151
+ vectors.
152
+
153
+ The embedding contains three planes and a point, just like embed_3d_object().
154
+
155
+ Parameters
156
+ ----------
157
+ position : torch.Tensor with shape (..., 1, 3)
158
+ Position in 3D space.
159
+ orientation : torch.Tensor with shape (..., 1, 6)
160
+ Orientation in two-vec parameterization
161
+
162
+ Returns
163
+ -------
164
+ multivector : torch.Tensor with shape (..., 4, 16)
165
+ Embedding into three multivectors.
166
+ """
167
+
168
+ # Check inputs
169
+ assert position.shape[-2:] == (1, 3)
170
+ assert orientation.shape[-2:] == (1, 6)
171
+
172
+ # Point
173
+ point_embedding = embed_point(position) # (..., 1, 16)
174
+
175
+ # Two-vec -> three vectors
176
+ orientation = orientation.reshape(*orientation.shape[:-2], 2, 3)
177
+ third_vec = torch.linalg.cross(orientation[..., [0], :], orientation[..., [1], :])
178
+ orientation = torch.cat((orientation, third_vec), dim=-2)
179
+
180
+ # Embed orientation as planes
181
+ orientation_embedding = embed_oriented_plane(orientation, position) # (..., 3, 16)
182
+
183
+ embedding = torch.cat((point_embedding, orientation_embedding), dim=-2) # (..., 4, 16)
184
+ return embedding
185
+
186
+
187
+ def extract_3d_object_two_vec(multivector: torch.Tensor) -> torch.Tensor:
188
+ """Extracts 3D position and two-vec orientation from the multivector embedding of an object.
189
+
190
+ This inverts embed_3d_object_two_vec().
191
+
192
+ Parameters
193
+ ----------
194
+ multivector : torch.Tensor with shape (..., 3, 16)
195
+ Object embedding.
196
+
197
+ Returns
198
+ -------
199
+ position : torch.Tensor with shape (..., 1, 3)
200
+ Position in 3D space.
201
+ orientation : torch.Tensor with shape (..., 1, 6)
202
+ Two-vec param of orientation
203
+ """
204
+
205
+ # Position
206
+ position = extract_point(multivector[..., [0], :]) # (..., 1, 3)
207
+
208
+ # Orientation
209
+ orientation = extract_oriented_plane(multivector[..., [1, 2], :]) # (..., 2, 3)
210
+ orientation = orientation.reshape(*multivector.shape[:-2], 1, 6) # (..., 1, 6)
211
+
212
+ return position, orientation
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/plane.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+ from torch import Tensor
5
+
6
+ from gatr.interface.translation import embed_translation
7
+ from gatr.primitives.bilinear import geometric_product
8
+
9
+
10
+ def embed_oriented_plane(normal: Tensor, position: Tensor) -> Tensor:
11
+ """Embeds an (oriented plane) in the PGA.
12
+
13
+ Following L. Dorst, the plane is represent as PGA vectors.
14
+
15
+ References
16
+ ----------
17
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
18
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
19
+
20
+ Parameters
21
+ ----------
22
+ normal : torch.Tensor with shape (..., 3)
23
+ Normal to the plane.
24
+ position : torch.Tensor with shape (..., 3)
25
+ One position on the plane.
26
+
27
+ Returns
28
+ -------
29
+ multivector : torch.Tensor with shape (..., 16)
30
+ Embedding into multivector.
31
+ """
32
+
33
+ # Create multivector tensor with same batch shape, same device, same dtype as input
34
+ batch_shape = normal.shape[:-1]
35
+ multivector = torch.zeros(*batch_shape, 16, dtype=normal.dtype, device=normal.device)
36
+
37
+ # Embedding a plane through origin into vectors
38
+ multivector[..., 2:5] = normal[..., :]
39
+
40
+ # Shift away from origin by translating
41
+ translation = embed_translation(position)
42
+ inverse_translation = embed_translation(-position)
43
+ multivector = geometric_product(
44
+ geometric_product(translation, multivector), inverse_translation
45
+ )
46
+
47
+ return multivector
48
+
49
+
50
+ def extract_oriented_plane(multivector: torch.Tensor) -> torch.Tensor:
51
+ """Extracts the normal on an oriented plane from a multivector.
52
+
53
+ Currently, this function does *not* extract a support point for the plane (or the distance to
54
+ the origin).
55
+
56
+ References
57
+ ----------
58
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
59
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
60
+
61
+ Parameters
62
+ ----------
63
+ multivector : torch.Tensor with shape (..., 16)
64
+ Embedding into multivector.
65
+
66
+ Returns
67
+ -------
68
+ normal : torch.Tensor with shape (..., 3)
69
+ Normal to the plane.
70
+ """
71
+
72
+ return multivector[..., 2:5]
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/point.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ """Functions that embed points in the geometric algebra."""
4
+
5
+
6
+ import torch
7
+
8
+
9
+ def embed_point(coordinates: torch.Tensor) -> torch.Tensor:
10
+ """Embeds 3D points in multivectors.
11
+
12
+ We follow the convention used in the reference below and map points to tri-vectors.
13
+
14
+ References
15
+ ----------
16
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
17
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
18
+
19
+ Parameters
20
+ ----------
21
+ coordinates : torch.Tensor with shape (..., 3)
22
+ 3D coordinates
23
+
24
+ Returns
25
+ -------
26
+ multivector : torch.Tensor with shape (..., 16)
27
+ Embedding into multivector.
28
+ """
29
+
30
+ # Create multivector tensor with same batch shape, same device, same dtype as input
31
+ batch_shape = coordinates.shape[:-1]
32
+ multivector = torch.zeros(*batch_shape, 16, dtype=coordinates.dtype, device=coordinates.device)
33
+
34
+ # Embedding into trivectors
35
+ # Homogeneous coordinates: unphysical component / embedding dim, x_123
36
+ multivector[..., 14] = 1.0
37
+ multivector[..., 13] = -coordinates[..., 0] # x-coordinate embedded in x_023
38
+ multivector[..., 12] = coordinates[..., 1] # y-coordinate embedded in x_013
39
+ multivector[..., 11] = -coordinates[..., 2] # z-coordinate embedded in x_012
40
+
41
+ return multivector
42
+
43
+
44
+ def extract_point(
45
+ multivector: torch.Tensor, divide_by_embedding_dim: bool = True, threshold: float = 1e-3
46
+ ) -> torch.Tensor:
47
+ """Given a multivector, extract any potential 3D point from the trivector components.
48
+
49
+ References
50
+ ----------
51
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
52
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
53
+
54
+ Parameters
55
+ ----------
56
+ multivector : torch.Tensor with shape (..., 16)
57
+ Multivector.
58
+ divide_by_embedding_dim : bool
59
+ Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it
60
+ may not be good for NN training.
61
+ threshold : float
62
+ Minimum value of the additional, unphysical component. Necessary to avoid exploding values
63
+ or NaNs when this unphysical component of the homogeneous coordinates becomes small.
64
+
65
+ Returns
66
+ -------
67
+ coordinates : torch.Tensor with shape (..., 3)
68
+ 3D coordinates corresponding to the trivector components of the multivector.
69
+ """
70
+
71
+ coordinates = torch.cat(
72
+ [-multivector[..., [13]], multivector[..., [12]], -multivector[..., [11]]], dim=-1
73
+ )
74
+
75
+ # Divide by embedding dim
76
+ if divide_by_embedding_dim:
77
+ embedding_dim = multivector[
78
+ ..., [14]
79
+ ] # Embedding dimension / scale of homogeneous coordinates
80
+ embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold)
81
+ coordinates = coordinates / embedding_dim
82
+
83
+ return coordinates
84
+
85
+
86
+ def extract_point_embedding_reg(multivector: torch.Tensor) -> torch.Tensor:
87
+ """Given a multivector x, returns |x_{123}| - 1.
88
+
89
+ Put differently, this is the deviation of the norm of a pseudoscalar component from 1.
90
+ This can be used as a regularization term when predicting point positions, to avoid x_123 to
91
+ be too close to 0.
92
+
93
+ Parameters
94
+ ----------
95
+ multivector : torch.Tensor with shape (..., 16)
96
+ Multivector.
97
+
98
+ Returns
99
+ -------
100
+ regularization : torch.Tensor with shape (..., 1)
101
+ |multivector_123| - 1.
102
+ """
103
+
104
+ return torch.abs(multivector[..., [14]]) - 1.0
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/pseudoscalar.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+
5
+
6
+ def embed_pseudoscalar(pseudoscalars: torch.Tensor) -> torch.Tensor:
7
+ """Embeds a pseudoscalar tensor into multivectors.
8
+
9
+ Parameters
10
+ ----------
11
+ pseudoscalars: torch.Tensor with shape (..., 1)
12
+ Pseudoscalar inputs.
13
+
14
+ Returns
15
+ -------
16
+ multivectors: torch.Tensor with shape (..., 16)
17
+ Multivector outputs. `multivectors[..., [15]]` is the same as `pseudoscalars`.
18
+ The other components are zero.
19
+ """
20
+
21
+ non_scalar_shape = list(pseudoscalars.shape[:-1]) + [15]
22
+ non_scalar_components = torch.zeros(
23
+ non_scalar_shape, device=pseudoscalars.device, dtype=pseudoscalars.dtype
24
+ )
25
+ embedding = torch.cat((non_scalar_components, pseudoscalars), dim=-1)
26
+
27
+ return embedding
28
+
29
+
30
+ def extract_pseudoscalar(multivectors: torch.Tensor) -> torch.Tensor:
31
+ """Extracts pseudoscalar components from multivectors.
32
+
33
+ Parameters
34
+ ----------
35
+ multivectors: torch.Tensor with shape (..., 16)
36
+ Multivector inputs.
37
+
38
+ Returns
39
+ -------
40
+ pseudoscalars: torch.Tensor with shape (..., 1)
41
+ Pseudoscalar component of multivectors.
42
+ """
43
+
44
+ return multivectors[..., [15]]
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/reflection.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ """Functions that create multivectors representing elements of the Pin group."""
4
+
5
+
6
+ from torch import Tensor
7
+
8
+ from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane
9
+
10
+
11
+ def embed_reflection(normal: Tensor, position: Tensor) -> Tensor:
12
+ """Embeds the reflection on a plane in multivectors.
13
+
14
+ Following L. Dorst, this is represented as a PGA vector.
15
+
16
+ References
17
+ ----------
18
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
19
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
20
+
21
+ Parameters
22
+ ----------
23
+ normal : Tensor with shape (..., 3)
24
+ Normal to the reflection plane.
25
+ position : Tensor with shape (..., 3)
26
+ One position on the reflection plane.
27
+
28
+ Returns
29
+ -------
30
+ multivector : Tensor with shape (..., 16)
31
+ Embedding into multivector.
32
+ """
33
+
34
+ return embed_oriented_plane(normal, position)
35
+
36
+
37
+ def extract_reflection(multivector: Tensor) -> Tensor:
38
+ """Extracts the normal on an reflection plane from a multivector.
39
+
40
+ References
41
+ ----------
42
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
43
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
44
+
45
+ Parameters
46
+ ----------
47
+ multivector : torch.Tensor with shape (..., 16)
48
+ Embedding into multivector.
49
+
50
+ Returns
51
+ -------
52
+ normal : torch.Tensor with shape (..., 3)
53
+ Normal to the plane.
54
+ """
55
+
56
+ return extract_oriented_plane(multivector)
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/rotation.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+
5
+
6
+ def embed_rotation(quaternion: torch.Tensor) -> torch.Tensor:
7
+ """Embeds 3D rotations in multivectors.
8
+
9
+ We follow the convention used in Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra
10
+ PGA", and map rotations around the origin to bivectors.
11
+
12
+ For quaternions we use the "Hamilton" convention, where ijk = -1 (*not* the JPL convention
13
+ where ijk = 1). For details, see "Why and How to Avoid the Flipped Quaternion Multiplication"
14
+ by Sommer et al. (2018)
15
+
16
+ References
17
+ ----------
18
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
19
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
20
+ Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478
21
+
22
+ Parameters
23
+ ----------
24
+ quaternion : torch.Tensor with shape (..., 4)
25
+ Quaternions in ijkw order and Hamilton convention (ijk=-1)
26
+
27
+ Returns
28
+ -------
29
+ multivector : torch.Tensor with shape (..., 16)
30
+ Embedding into multivector.
31
+ """
32
+ # Create multivector tensor with same batch shape, same device, same dtype as input
33
+ batch_shape = quaternion.shape[:-1]
34
+ multivector = torch.zeros(*batch_shape, 16, dtype=quaternion.dtype, device=quaternion.device)
35
+
36
+ # Embedding into bivectors
37
+ # w component of quaternion is the scalar component of the multivector
38
+ multivector[..., 0] = quaternion[..., 3]
39
+ multivector[..., 8] = -quaternion[..., 2] # k component of quaternion is the bivector -e12
40
+ multivector[..., 9] = quaternion[..., 1] # j component of quaternion is the bivector e13
41
+ multivector[..., 10] = -quaternion[..., 0] # i component of quaternion is the bivector -e23
42
+
43
+ return multivector
44
+
45
+
46
+ def extract_rotation(multivector: torch.Tensor, normalize: bool = False) -> torch.Tensor:
47
+ """Extracts the represented rotation quaternion from the multivector's bivector components.
48
+
49
+ Parameters
50
+ ----------
51
+ multivector : torch.Tensor with shape (..., 16)
52
+ Multivector.
53
+ normalize : bool
54
+ Whether to normalize the quaternion to unit norm.
55
+
56
+ Returns
57
+ -------
58
+ quaternion : torch.Tensor with shape (..., 4)
59
+ quaternion in ijkw order and Hamilton convention (ijk = -1)
60
+ """
61
+
62
+ quaternion = torch.cat(
63
+ [
64
+ -multivector[..., [10]],
65
+ multivector[..., [9]],
66
+ -multivector[..., [8]],
67
+ multivector[..., [0]],
68
+ ],
69
+ dim=-1,
70
+ )
71
+
72
+ if normalize:
73
+ quaternion = quaternion / torch.linalg.norm(quaternion, dim=-1, keepdim=True)
74
+
75
+ return quaternion
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/scalar.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+
5
+
6
+ def embed_scalar(scalars: torch.Tensor) -> torch.Tensor:
7
+ """Embeds a scalar tensor into multivectors.
8
+
9
+ Parameters
10
+ ----------
11
+ scalars: torch.Tensor with shape (..., 1)
12
+ Scalar inputs.
13
+
14
+ Returns
15
+ -------
16
+ multivectors: torch.Tensor with shape (..., 16)
17
+ Multivector outputs. `multivectors[..., [0]]` is the same as `scalars`. The other components
18
+ are zero.
19
+ """
20
+
21
+ non_scalar_shape = list(scalars.shape[:-1]) + [15]
22
+ non_scalar_components = torch.zeros(
23
+ non_scalar_shape, device=scalars.device, dtype=scalars.dtype
24
+ )
25
+ embedding = torch.cat((scalars, non_scalar_components), dim=-1)
26
+
27
+ return embedding
28
+
29
+
30
+ def extract_scalar(multivectors: torch.Tensor) -> torch.Tensor:
31
+ """Extracts scalar components from multivectors.
32
+
33
+ Parameters
34
+ ----------
35
+ multivectors: torch.Tensor with shape (..., 16)
36
+ Multivector inputs.
37
+
38
+ Returns
39
+ -------
40
+ scalars: torch.Tensor with shape (..., 1)
41
+ Scalar component of multivectors.
42
+ """
43
+
44
+ return multivectors[..., [0]]
gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/translation.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+
5
+
6
+ def embed_translation(translation_vector: torch.Tensor) -> torch.Tensor:
7
+ """Embeds a 3D translation in multivectors.
8
+
9
+ In our convention, a translation vector is embedded into a combination of the scalar and
10
+ bivector components.
11
+
12
+ We have (in agreement with Eq. (82) of the reference below) that
13
+ ```
14
+ T(t) = 1 - e_0 / 2 (t_1 e_1 + t_2 e_2 + t_3 e_3) .
15
+ ```
16
+
17
+ References
18
+ ----------
19
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
20
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
21
+
22
+ Parameters
23
+ ----------
24
+ translation_vector : torch.Tensor with shape (..., 3)
25
+ Vectorial amount of translation.
26
+
27
+ Returns
28
+ -------
29
+ multivector : torch.Tensor with shape (..., 16)
30
+ Embedding into multivector.
31
+ """
32
+
33
+ # Create multivector tensor with same batch shape, same device, same dtype as input
34
+ batch_shape = translation_vector.shape[:-1]
35
+ multivector = torch.zeros(
36
+ *batch_shape, 16, dtype=translation_vector.dtype, device=translation_vector.device
37
+ )
38
+
39
+ # Embedding into trivectors
40
+ multivector[..., 0] = 1.0 # scalar
41
+ multivector[..., 5:8] = (
42
+ -0.5 * translation_vector[..., :]
43
+ ) # Translation vector embedded in x_0i with i = 1, 2, 3
44
+
45
+ return multivector
46
+
47
+
48
+ def extract_translation(
49
+ multivector: torch.Tensor, divide_by_embedding_dim=False, threshold: float = 1e-3
50
+ ) -> torch.Tensor:
51
+ """Given a multivector, extract a 3D translation vector from the bivector components.
52
+
53
+ References
54
+ ----------
55
+ Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA",
56
+ https://geometricalgebra.org/downloads/PGA4CS.pdf
57
+
58
+ Parameters
59
+ ----------
60
+ multivector : torch.Tensor with shape (..., 16)
61
+ Multivector.
62
+ divide_by_embedding_dim : bool
63
+ Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it
64
+ may not be good for NN training.
65
+ threshold : float
66
+ Minimum value of the additional, unphysical component. Necessary to avoid exploding values
67
+ or NaNs when this unphysical component of the homogeneous coordinates becomes small.
68
+
69
+ Returns
70
+ -------
71
+ translation : torch.Tensor with shape (..., 3)
72
+ 3D components of the translation vector.
73
+ """
74
+
75
+ translation_vector = -2.0 * multivector[..., 5:8]
76
+
77
+ # Divide by embedding dim
78
+ if divide_by_embedding_dim:
79
+ embedding_dim = multivector[..., [0]]
80
+ embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold)
81
+ translation_vector = translation_vector / embedding_dim
82
+
83
+ return translation_vector
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .attention.config import SelfAttentionConfig
4
+ from .attention.positional_encoding import ApplyRotaryPositionalEncoding
5
+ from .attention.self_attention import SelfAttention
6
+ from .dropout import GradeDropout
7
+ from .layer_norm import EquiLayerNorm
8
+ from .linear import EquiLinear
9
+ from .mlp.geometric_bilinears import GeometricBilinear
10
+ from .mlp.mlp import GeoMLP
11
+ from .mlp.nonlinearities import ScalarGatedNonlinearity
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from .config import SelfAttentionConfig
4
+ from .self_attention import SelfAttention
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/attention.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ """Self-attention layers."""
4
+
5
+ from functools import partial
6
+
7
+ import torch
8
+ from torch import nn
9
+
10
+ from gatr.layers.attention.config import SelfAttentionConfig
11
+ from gatr.primitives.attention import geometric_attention, lin_square_normalizer
12
+
13
+
14
+ class GeometricAttention(nn.Module):
15
+ """Geometric attention layer.
16
+
17
+ This is the main attention mechanism used in GATr. Thanks to the nonlinear features, the
18
+ scaled-dot-product attention takes into account the Euclidean distance.
19
+
20
+ Given multivector and scalar queries, keys, and values, this layer computes:
21
+
22
+ ```
23
+ attn_weights[..., i, j] = softmax_j[
24
+ weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :])
25
+ + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :]))
26
+ + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :])
27
+ ]
28
+ out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm
29
+ out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm
30
+ ```
31
+
32
+ Parameters
33
+ ----------
34
+ config : SelfAttentionConfig
35
+ Attention configuration.
36
+ """
37
+
38
+ def __init__(self, config: SelfAttentionConfig) -> None:
39
+ super().__init__()
40
+
41
+ self.normalizer = partial(lin_square_normalizer, epsilon=config.normalizer_eps)
42
+ self.log_weights = nn.Parameter(
43
+ torch.zeros((config.num_heads, 1, config.hidden_mv_channels))
44
+ )
45
+
46
+ def forward(self, q_mv, k_mv, v_mv, q_s, k_s, v_s, attention_mask=None):
47
+ """Forward pass through geometric attention.
48
+
49
+ Given multivector and scalar queries, keys, and values, this forward pass computes:
50
+
51
+ ```
52
+ attn_weights[..., i, j] = softmax_j[
53
+ weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :])
54
+ + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :]))
55
+ + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :])
56
+ ]
57
+ out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm
58
+ out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm
59
+ ```
60
+
61
+ Parameters
62
+ ----------
63
+ q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16)
64
+ Queries, multivector part.
65
+ k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16)
66
+ Keys, multivector part.
67
+ v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16)
68
+ Values, multivector part.
69
+ q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in)
70
+ Queries, scalar part.
71
+ k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in)
72
+ Keys, scalar part.
73
+ v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out)
74
+ Values, scalar part.
75
+ attention_mask: None or Tensor or AttentionBias
76
+ Optional attention mask.
77
+ """
78
+
79
+ weights = self.log_weights.exp()
80
+ h_mv, h_s = geometric_attention(
81
+ q_mv,
82
+ k_mv,
83
+ v_mv,
84
+ q_s,
85
+ k_s,
86
+ v_s,
87
+ normalizer=self.normalizer,
88
+ weights=weights,
89
+ attn_mask=attention_mask,
90
+ )
91
+
92
+ return h_mv, h_s
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/config.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Mapping, Optional
7
+
8
+
9
+ @dataclass
10
+ class SelfAttentionConfig:
11
+ """Configuration for attention.
12
+
13
+ Parameters
14
+ ----------
15
+ in_mv_channels : int
16
+ Number of input multivector channels.
17
+ out_mv_channels : int
18
+ Number of output multivector channels.
19
+ num_heads : int
20
+ Number of attention heads.
21
+ in_s_channels : int
22
+ Input scalar channels. If None, no scalars are expected nor returned.
23
+ out_s_channels : int
24
+ Output scalar channels. If None, no scalars are expected nor returned.
25
+ additional_qk_mv_channels : int
26
+ Whether additional multivector features for the keys and queries will be provided.
27
+ additional_qk_s_channels : int
28
+ Whether additional scalar features for the keys and queries will be provided.
29
+ normalizer : str
30
+ Normalizer function to use in sdp_dist attention
31
+ normalizer_eps : float
32
+ Small umerical constant for stability in the normalizer in sdp_dist attention
33
+ multi_query: bool
34
+ Whether to do multi-query attention
35
+ attention_type : {"scalar", "geometric", "sdp_dist"}
36
+ Whether the attention mechanism is based on the scalar product or also the join.
37
+ pos_encoding : bool
38
+ Whether to apply rotary positional embeddings along the item dimension to the scalar keys
39
+ and queries.
40
+ pos_enc_base : int
41
+ Base for the frequencies in the positional encoding.
42
+ output_init : str
43
+ Initialization scheme for final linear layer
44
+ increase_hidden_channels : int
45
+ Factor by which to increase the number of hidden channels (both multivectors and scalars)
46
+ dropout_prob : float or None
47
+ Dropout probability
48
+ """
49
+
50
+ multi_query: bool = True
51
+ in_mv_channels: Optional[int] = None
52
+ out_mv_channels: Optional[int] = None
53
+ in_s_channels: Optional[int] = None
54
+ out_s_channels: Optional[int] = None
55
+ num_heads: int = 8
56
+ additional_qk_mv_channels: int = 0
57
+ additional_qk_s_channels: int = 0
58
+ normalizer_eps: Optional[float] = 1e-3
59
+ pos_encoding: bool = False
60
+ pos_enc_base: int = 4096
61
+ output_init: str = "default"
62
+ checkpoint: bool = True
63
+ increase_hidden_channels: int = 2
64
+ dropout_prob: Optional[float] = None
65
+
66
+ def __post_init__(self):
67
+ """Type checking / conversion."""
68
+ if isinstance(self.dropout_prob, str) and self.dropout_prob.lower() in ["null", "none"]:
69
+ self.dropout_prob = None
70
+
71
+ @property
72
+ def hidden_mv_channels(self) -> Optional[int]:
73
+ """Returns the number of hidden multivector channels."""
74
+
75
+ if self.in_mv_channels is None:
76
+ return None
77
+
78
+ return max(self.increase_hidden_channels * self.in_mv_channels // self.num_heads, 1)
79
+
80
+ @property
81
+ def hidden_s_channels(self) -> Optional[int]:
82
+ """Returns the number of hidden scalar channels."""
83
+
84
+ if self.in_s_channels is None:
85
+ return None
86
+
87
+ hidden_s_channels = max(
88
+ self.increase_hidden_channels * self.in_s_channels // self.num_heads, 4
89
+ )
90
+
91
+ # When using positional encoding, the number of scalar hidden channels needs to be even.
92
+ # It also should not be too small.
93
+ if self.pos_encoding:
94
+ hidden_s_channels = (hidden_s_channels + 1) // 2 * 2
95
+ hidden_s_channels = max(hidden_s_channels, 8)
96
+
97
+ return hidden_s_channels
98
+
99
+ @classmethod
100
+ def cast(cls, config: Any) -> SelfAttentionConfig:
101
+ """Casts an object as SelfAttentionConfig."""
102
+ if isinstance(config, SelfAttentionConfig):
103
+ return config
104
+ if isinstance(config, Mapping):
105
+ return cls(**config)
106
+ raise ValueError(f"Can not cast {config} to {cls}")
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/positional_encoding.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+
4
+ """Adapted from the below.
5
+
6
+ https://github.com/EleutherAI/gpt-neox/blob/737c9134bfaff7b58217d61f6619f1dcca6c484f/megatron/model/positional_embeddings.py
7
+ by EleutherAI at https://github.com/EleutherAI/gpt-neox
8
+
9
+ Copyright (c) 2021, EleutherAI
10
+
11
+ Licensed under the Apache License, Version 2.0 (the "License");
12
+ you may not use this file except in compliance with the License.
13
+ You may obtain a copy of the License at
14
+
15
+ http://www.apache.org/licenses/LICENSE-2.0
16
+
17
+ Unless required by applicable law or agreed to in writing, software
18
+ distributed under the License is distributed on an "AS IS" BASIS,
19
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ See the License for the specific language governing permissions and
21
+ limitations under the License.
22
+ """
23
+
24
+ import torch
25
+
26
+ from gatr.utils.einsum import cached_einsum
27
+
28
+
29
+ class ApplyRotaryPositionalEncoding(torch.nn.Module):
30
+ """Applies rotary position encodings (RoPE) to scalar tensors.
31
+
32
+ References
33
+ ----------
34
+ Jianlin Su et al, "RoFormer: Enhanced Transformer with Rotary Position Embedding",
35
+ arXiv:2104.09864
36
+
37
+ Parameters
38
+ ----------
39
+ num_channels : int
40
+ Number of channels (key and query size).
41
+ item_dim : int
42
+ Embedding dimension. Should be even.
43
+ base : int
44
+ Determines the frequencies.
45
+ """
46
+
47
+ def __init__(self, num_channels, item_dim, base=4096):
48
+ super().__init__()
49
+
50
+ assert (
51
+ num_channels % 2 == 0
52
+ ), "Number of channels needs to be even for rotary position embeddings"
53
+
54
+ inv_freq = 1.0 / (base ** (torch.arange(0, num_channels, 2).float() / num_channels))
55
+ self.register_buffer("inv_freq", inv_freq)
56
+ self.seq_len_cached = None
57
+ self.device_cached = None
58
+ self.cos_cached = None
59
+ self.sin_cached = None
60
+ self.item_dim = item_dim
61
+ self.num_channels = num_channels
62
+
63
+ def forward(self, scalars: torch.Tensor) -> torch.Tensor:
64
+ """Computes rotary embeddings along `self.item_dim` and applies them to inputs.
65
+
66
+ The inputs are usually scalar queries and keys.
67
+
68
+ Assumes that the last dimension is the feature dimension (and is thus not suited
69
+ for multivector data!).
70
+
71
+ Parameters
72
+ ----------
73
+ scalars : torch.Tensor of shape (..., num_channels)
74
+ Input data. The last dimension is assumed to be the channel / feature dimension
75
+ (NOT the 16 dimensions of a multivector).
76
+
77
+ Returns
78
+ -------
79
+ outputs : torch.Tensor of shape (..., num_channels)
80
+ Output data. Rotary positional embeddings applied to the input tensor.
81
+ """
82
+
83
+ # Check inputs
84
+ assert scalars.shape[-1] == self.num_channels
85
+
86
+ # Compute embeddings, if not already cached
87
+ self._compute_embeddings(scalars)
88
+
89
+ # Apply embeddings
90
+ outputs = scalars * self.cos_cached + self._rotate_half(scalars) * self.sin_cached
91
+
92
+ return outputs
93
+
94
+ def _compute_embeddings(self, inputs):
95
+ """Computes position embeddings and stores them.
96
+
97
+ The position embedding is computed along dimension `item_dim` of tensor `inputs`
98
+ and is stored in `self.sin_cached` and `self.cos_cached`.
99
+
100
+ Parameters
101
+ ----------
102
+ inputs : torch.Tensor
103
+ Input data.
104
+ """
105
+ seq_len = inputs.shape[self.item_dim]
106
+ if seq_len != self.seq_len_cached or inputs.device != self.device_cached:
107
+ self.seq_len_cached = seq_len
108
+ self.device_cached = inputs.device
109
+ t = torch.arange(inputs.shape[self.item_dim], device=inputs.device).type_as(
110
+ self.inv_freq
111
+ )
112
+ freqs = cached_einsum("i,j->ij", t, self.inv_freq)
113
+ emb = torch.cat((freqs, freqs), dim=-1).to(inputs.device)
114
+
115
+ self.cos_cached = emb.cos()
116
+ self.sin_cached = emb.sin()
117
+
118
+ # Insert appropriate amount of dimensions such that the embedding correctly enumerates
119
+ # along the item dim
120
+ item_dim = (
121
+ self.item_dim if self.item_dim >= 0 else inputs.ndim + self.item_dim
122
+ ) # Deal with item_dim < 0
123
+ for _ in range(item_dim + 1, inputs.ndim - 1):
124
+ self.cos_cached = self.cos_cached.unsqueeze(1)
125
+ self.sin_cached = self.sin_cached.unsqueeze(1)
126
+
127
+ @staticmethod
128
+ def _rotate_half(inputs):
129
+ """Utility function that "rotates" a tensor, as required for rotary embeddings."""
130
+ x1, x2 = inputs[..., : inputs.shape[-1] // 2], inputs[..., inputs.shape[-1] // 2 :]
131
+ return torch.cat((-x2, x1), dim=-1)
gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/qkv.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023 Qualcomm Technologies, Inc.
2
+ # All rights reserved.
3
+ import torch
4
+ from einops import rearrange
5
+ from torch import nn
6
+
7
+ from gatr.layers.attention.config import SelfAttentionConfig
8
+ from gatr.layers.linear import EquiLinear
9
+
10
+
11
+ class QKVModule(nn.Module):
12
+ """Compute (multivector and scalar) queries, keys, and values via multi-head attention.
13
+
14
+ Parameters
15
+ ----------
16
+ config: SelfAttentionConfig
17
+ Attention configuration
18
+ """
19
+
20
+ def __init__(self, config: SelfAttentionConfig):
21
+ super().__init__()
22
+ self.in_linear = EquiLinear(
23
+ in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels,
24
+ out_mv_channels=3 * config.hidden_mv_channels * config.num_heads,
25
+ in_s_channels=config.in_s_channels + config.additional_qk_s_channels,
26
+ out_s_channels=None
27
+ if config.in_s_channels is None
28
+ else 3 * config.hidden_s_channels * config.num_heads,
29
+ )
30
+ self.config = config
31
+
32
+ def forward(
33
+ self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None
34
+ ):
35
+ """Forward pass.
36
+
37
+ Parameters
38
+ ----------
39
+ inputs : torch.Tensor
40
+ Multivector inputs
41
+ scalars : torch.Tensor
42
+ Scalar inputs
43
+ additional_qk_features_mv : None or torch.Tensor
44
+ Additional multivector features that should be provided for the Q/K computation (e.g.
45
+ positions of objects)
46
+ additional_qk_features_s : None or torch.Tensor
47
+ Additional scalar features that should be provided for the Q/K computation (e.g.
48
+ object types)
49
+
50
+ Returns
51
+ -------
52
+ q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16)
53
+ Queries, multivector part.
54
+ k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16)
55
+ Keys, multivector part.
56
+ v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16)
57
+ Values, multivector part.
58
+ q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in)
59
+ Queries, scalar part.
60
+ k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in)
61
+ Keys, scalar part.
62
+ v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out)
63
+ Values, scalar part.
64
+ """
65
+
66
+ # Additional inputs
67
+ if additional_qk_features_mv is not None:
68
+ inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2)
69
+ if additional_qk_features_s is not None:
70
+ scalars = torch.cat((scalars, additional_qk_features_s), dim=-1)
71
+
72
+ qkv_mv, qkv_s = self.in_linear(
73
+ inputs, scalars
74
+ ) # (..., num_items, 3 * hidden_channels * num_heads, 16)
75
+ qkv_mv = rearrange(
76
+ qkv_mv,
77
+ "... items (qkv hidden num_heads) x -> qkv ... num_heads items hidden x",
78
+ num_heads=self.config.num_heads,
79
+ hidden=self.config.hidden_mv_channels,
80
+ qkv=3,
81
+ )
82
+ q_mv, k_mv, v_mv = qkv_mv # each: (..., num_heads, num_items, num_channels, 16)
83
+
84
+ # Same, for optional scalar components
85
+ if qkv_s is not None:
86
+ qkv_s = rearrange(
87
+ qkv_s,
88
+ "... items (qkv hidden num_heads) -> qkv ... num_heads items hidden",
89
+ num_heads=self.config.num_heads,
90
+ hidden=self.config.hidden_s_channels,
91
+ qkv=3,
92
+ )
93
+ q_s, k_s, v_s = qkv_s # each: (..., num_heads, num_items, num_channels)
94
+ else:
95
+ q_s, k_s, v_s = None, None, None
96
+
97
+ return q_mv, k_mv, v_mv, q_s, k_s, v_s
98
+
99
+
100
+ class MultiQueryQKVModule(nn.Module):
101
+ """Compute (multivector and scalar) queries, keys, and values via multi-query attention.
102
+
103
+ Parameters
104
+ ----------
105
+ config: SelfAttentionConfig
106
+ Attention configuration
107
+ """
108
+
109
+ def __init__(self, config: SelfAttentionConfig):
110
+ super().__init__()
111
+
112
+ # Q projection
113
+ self.q_linear = EquiLinear(
114
+ in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels,
115
+ out_mv_channels=config.hidden_mv_channels * config.num_heads,
116
+ in_s_channels=config.in_s_channels + config.additional_qk_s_channels,
117
+ out_s_channels=config.hidden_s_channels * config.num_heads,
118
+ )
119
+
120
+ # Key and value projections (shared between heads)
121
+ self.k_linear = EquiLinear(
122
+ in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels,
123
+ out_mv_channels=config.hidden_mv_channels,
124
+ in_s_channels=config.in_s_channels + config.additional_qk_s_channels,
125
+ out_s_channels=config.hidden_s_channels,
126
+ )
127
+ self.v_linear = EquiLinear(
128
+ in_mv_channels=config.in_mv_channels,
129
+ out_mv_channels=config.hidden_mv_channels,
130
+ in_s_channels=config.in_s_channels,
131
+ out_s_channels=config.hidden_s_channels,
132
+ )
133
+ self.config = config
134
+
135
+ def forward(
136
+ self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None
137
+ ):
138
+ """Forward pass.
139
+
140
+ Parameters
141
+ ----------
142
+ inputs : torch.Tensor
143
+ Multivector inputs
144
+ scalars : torch.Tensor
145
+ Scalar inputs
146
+ additional_qk_features_mv : None or torch.Tensor
147
+ Additional multivector features that should be provided for the Q/K computation (e.g.
148
+ positions of objects)
149
+ additional_qk_features_s : None or torch.Tensor
150
+ Additional scalar features that should be provided for the Q/K computation (e.g.
151
+ object types)
152
+
153
+ Returns
154
+ -------
155
+ q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16)
156
+ Queries, multivector part.
157
+ k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16)
158
+ Keys, multivector part.
159
+ v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16)
160
+ Values, multivector part.
161
+ q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in)
162
+ Queries, scalar part.
163
+ k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in)
164
+ Keys, scalar part.
165
+ v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out)
166
+ Values, scalar part.
167
+ """
168
+
169
+ # Additional inputs
170
+ if additional_qk_features_mv is not None:
171
+ qk_inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2)
172
+ else:
173
+ qk_inputs = inputs
174
+ if scalars is not None and additional_qk_features_s is not None:
175
+ qk_scalars = torch.cat((scalars, additional_qk_features_s), dim=-1)
176
+ else:
177
+ qk_scalars = scalars
178
+
179
+ # Project to queries, keys, and values (multivector reps)
180
+ q_mv, q_s = self.q_linear(
181
+ qk_inputs, qk_scalars
182
+ ) # (..., num_items, hidden_channels * num_heads, 16)
183
+ k_mv, k_s = self.k_linear(qk_inputs, qk_scalars) # (..., num_items, hidden_channels, 16)
184
+ v_mv, v_s = self.v_linear(inputs, scalars) # (..., num_items, hidden_channels, 16)
185
+
186
+ # Rearrange to (..., heads, items, channels, 16) shape
187
+ q_mv = rearrange(
188
+ q_mv,
189
+ "... items (hidden_channels num_heads) x -> ... num_heads items hidden_channels x",
190
+ num_heads=self.config.num_heads,
191
+ hidden_channels=self.config.hidden_mv_channels,
192
+ )
193
+ k_mv = rearrange(k_mv, "... items hidden_channels x -> ... 1 items hidden_channels x")
194
+ v_mv = rearrange(v_mv, "... items hidden_channels x -> ... 1 items hidden_channels x")
195
+
196
+ # Same for scalars
197
+ if q_s is not None:
198
+ q_s = rearrange(
199
+ q_s,
200
+ "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels",
201
+ num_heads=self.config.num_heads,
202
+ hidden_channels=self.config.hidden_s_channels,
203
+ )
204
+ k_s = rearrange(k_s, "... items hidden_channels -> ... 1 items hidden_channels")
205
+ v_s = rearrange(v_s, "... items hidden_channels -> ... 1 items hidden_channels")
206
+ else:
207
+ q_s, k_s, v_s = None, None, None
208
+
209
+ return q_mv, k_mv, v_mv, q_s, k_s, v_s