diff --git a/gafl/.gitignore b/gafl/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4b704284d1f1ef980f75223eff7897ab661d5433 --- /dev/null +++ b/gafl/.gitignore @@ -0,0 +1,211 @@ +wandb/ +wandb*.json +**/*.ckpt +**/*.pth +**/*.json +.vscode/ +**/*.pdb +ckpt/ +*.code-workspace +outputs/ +**/*.txt +**/lightning_logs/ +**/inference_outputs/ +.hydra +scope_preprocessed/ +preprocessed/ +datasets/ +*.zip + +# job.sh + +slurm_logs/* +*.csv + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ +configs/hybrid_cascade.yaml +plots/ +test.py +ATLAS/ +*.sh +!install_gatr.sh +tmp/ +databases/ +dataset-* +outputs/ + + +scripts/logs/ +results/ + +# exclude .sh and .csv in scripts from gitignore: +!scripts/*.sh +!scripts/*.csv +metrics.csv + +notebooks/*.png +tensors/a.pt +tensors/o_pt.pt + +configs/data/ +.condarc +log \ No newline at end of file diff --git a/gafl/AUTHORS.md b/gafl/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..1aa7797391c6ab5005cfcc93da8bd4ae72586cd8 --- /dev/null +++ b/gafl/AUTHORS.md @@ -0,0 +1,6 @@ +Simon Wagner +Leif Seute +Vsevolod Viliuga +Nicolas Wolf +Frauke Gräter +Jan Stühmer \ No newline at end of file diff --git a/gafl/LICENSE b/gafl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e847e95bfd450234bf6b9f9a56e3f3a6e336a534 --- /dev/null +++ b/gafl/LICENSE @@ -0,0 +1,57 @@ +Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation +Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH + +Based on the code for + +Fast protein backbone generation with SE(3) flow matching +Copyright (c) Microsoft Corporation + +and + +Geometric Algebra Transformer +Copyright (c) 2023 Qualcomm Technologies, Inc. + +----------------------------------------------------------------------------- +MIT license + +applies to + +Fast protein backbone generation with SE(3) flow matching +Copyright (c) Microsoft Corporation + +Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation +Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH + +i.e. to all code in this repository except gafl/models/gafl/pga_utils.py. +----------------------------------------------------------------------------- + + +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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. + + +----------------------------------------------------------------------------- +3-Clause BSD License + +applies to derivative work based on + +Geometric Algebra Transformer +Copyright (c) 2023 Qualcomm Technologies, Inc. + +i.e. to gafl/models/gafl/pga_utils.py. + +Copyright (c) 2024 Heidelberg Institute for Theoretical Studies, HITS gGmbH +----------------------------------------------------------------------------- + +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: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer: + +* 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. + +* 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. + +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. diff --git a/gafl/NOTICE.md b/gafl/NOTICE.md new file mode 100644 index 0000000000000000000000000000000000000000..324a401f577c2bedd46aba88b67c3f6c52a6f5ad --- /dev/null +++ b/gafl/NOTICE.md @@ -0,0 +1,2 @@ +This project includes software from OpenFold (Apache 2.0) +https://github.com/aqlaboratory/openfold \ No newline at end of file diff --git a/gafl/README.md b/gafl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78c8418f3d3562dec50dd680dee1387245029a10 --- /dev/null +++ b/gafl/README.md @@ -0,0 +1,87 @@ +# Geometric Algebra Flow Matching (GAFL) for Protein Backbone Generation + +Source code for "Generating Highly Designable Proteins with Geometric Algebra Flow Matching" (https://arxiv.org/abs/2411.05238) + +If you use this code, please cite: + +``` +@inproceedings{wagnerseute2024gafl, + title={Generating Highly Designable Proteins with Geometric Algebra Flow Matching}, + author={Wagner, Simon and Seute, Leif and Viliuga, Vsevolod and Wolf, Nicolas and Gr{\"a}ter, Frauke and St{\"u}hmer, Jan}, + booktitle={Thirty-eighth Conference on Neural Information Processing Systems}, + year={2024} +} +``` + +This repository is based on FrameFlow (https://github.com/microsoft/protein-frame-flow). + +The datasets and weights of the models reported in the paper will be made available in the future + +# Installation + +### TLDR + +```bash +conda env create -f environment.yaml +conda activate gafl +bash install_gatr.sh # Apply patches to gatr + +# Install package: +pip install -e . +``` + +### Geometric Algebra Transformer +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. + +To install gatr with the required patches please run +``` +conda activate gafl +bash install_gatr.sh +``` + +### Install package +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 +```bash +pip install -e . +``` + +# Usage + +## Inference + +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 +```bash +python experiments/inference.py inference.ckpt_path= +``` + +You can specify the inference settings like the number of samples and timesteps via a config file like `configs/inference.yaml`. + +### Download model weights + +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: +```bash +mkdir -p outputs +wget https://github.com/hits-mli/gafl/releases/download/v1.0.0/gafl-pdb.zip +unzip gafl-pdb.zip -d outputs +python experiments/inference.py inference.ckpt_path=outputs/gafl-pdb/gafl321.ckpt +``` + + + +## Training + +To train the model on the scope dataset, paste the path to your metadata csv file in configs/data/default.yaml and run + +```bash +python experiments/train.py model=gafl +``` + +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 + +```bash +python experiments/train.py model=gafl data=pdb +``` + +### Download dataset + +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. diff --git a/gafl/build/geometric-algebra-transformer/.coveragerc b/gafl/build/geometric-algebra-transformer/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..40a823e09d703853ecb62d2294cb52889f4ff16b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/.coveragerc @@ -0,0 +1,2 @@ +[run] +omit = tests/*,scripts/*,gatr/experiments/* diff --git a/gafl/build/geometric-algebra-transformer/.dockerignore b/gafl/build/geometric-algebra-transformer/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..1b63bc0bc48205cf1bb7c640c1f2126c8ebc1186 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/.dockerignore @@ -0,0 +1,9 @@ +# pytest +.coverage +.pytest +.pytest_cache + +# Python +*__pycache__* +*.egg-info +*.py[cod] diff --git a/gafl/build/geometric-algebra-transformer/.gitignore b/gafl/build/geometric-algebra-transformer/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1b63bc0bc48205cf1bb7c640c1f2126c8ebc1186 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/.gitignore @@ -0,0 +1,9 @@ +# pytest +.coverage +.pytest +.pytest_cache + +# Python +*__pycache__* +*.egg-info +*.py[cod] diff --git a/gafl/build/geometric-algebra-transformer/.pylintrc b/gafl/build/geometric-algebra-transformer/.pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..b4240287bd0191ec85fb8cb29cda2fc4187ec917 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/.pylintrc @@ -0,0 +1,638 @@ +# .pylintrc generated on 2023-01-19 with pylint 2.15.10 + +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS,data + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\' represents the directory delimiter on Windows systems, it +# can't be used as an escape character. +ignore-paths=notebooks, docker + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins=pylint.extensions.docparams + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.8 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + x, + y, + z, + h, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=yes + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make, + _calculate_fan_in_and_fan_out, + _target_ + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=20 + +# Maximum number of attributes for a class (see R0902). +max-attributes=20 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=32 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=24 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=60 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=BaseException, + Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + missing-module-docstring, + use-symbolic-message-instead, + invalid-name, + too-few-public-methods, + logging-fstring-interpolation, + global-statement, + no-member, + no-value-for-parameter, + cell-var-from-loop, + invalid-unary-operand-type, + unbalanced-tuple-unpacking, + no-else-return, + missing-type-doc, + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +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 + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members=numpy.*, torch.* + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_|args|kwargs + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/gafl/build/geometric-algebra-transformer/CHANGELOG.md b/gafl/build/geometric-algebra-transformer/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c914c4a76013b3de8c45d177fb247ec830191846 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +## [1.2.0] - 2024-02-19 + +### Added + +- Expose `join_reference` kwarg in `GATr.forward()`, `AxialGATr.forward()` +- Add utility function `gatr.utils.compile_linear.compile_equi_linear_submodules()` + +### Removed + +- Remove option to *not* provide a position in `embed_oriented_plane()`, `embed_reflection()` + +## [1.1.1] - 2024-01-10 + +_Minor cleanup._ + +## [1.1.0] - 2024-01-02 + +### Changed + +- Change dimension collapse behaviour in `AxialGATr` and `BaselineAxialTransformer` + +### Added + +- Add hooks functionality and `register_hook()` method to `BaseExperiment` + +### Fixed + +- Fix critical bug in `embed_3d_object_two_vec()` that lead to wrong results when any tensor dimension was 3 +- Fix various minor issues in `BaseExperiment` +- Improve logging in `BaseExperiment` + +## [1.0.0] - 2023-10-19 + +_First release._ diff --git a/gafl/build/geometric-algebra-transformer/GATr.egg-info/PKG-INFO b/gafl/build/geometric-algebra-transformer/GATr.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..b36aaf8c08270d46c2cfc2b9e97533a106247741 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/GATr.egg-info/PKG-INFO @@ -0,0 +1,27 @@ +Metadata-Version: 2.4 +Name: GATr +Version: 1.2.0 +Summary: The Geometric Algebra Transformer, a universal neural network architecture for geometric data +Home-page: https://github.com/Qualcomm-AI-research/geometric-algebra-transformer +Author: Johann Brehmer, Pim de Haan, Sönke Behrends, and Taco Cohen +Author-email: jbrehmer@qti.qualcomm.com +Maintainer: Johann Brehmer +Maintainer-email: jbrehmer@qti.qualcomm.com +License: See notice in license file +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: einops +Requires-Dist: numpy<1.25 +Requires-Dist: opt_einsum @ git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10 +Requires-Dist: torch>=2.0 +Requires-Dist: xformers +Dynamic: author +Dynamic: author-email +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary diff --git a/gafl/build/geometric-algebra-transformer/GATr.egg-info/SOURCES.txt b/gafl/build/geometric-algebra-transformer/GATr.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9abe18f652275c3fe60a3479f1ca413f2b74e39 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/GATr.egg-info/SOURCES.txt @@ -0,0 +1,80 @@ +LICENSE +README.md +pyproject.toml +setup.py +GATr.egg-info/PKG-INFO +GATr.egg-info/SOURCES.txt +GATr.egg-info/dependency_links.txt +GATr.egg-info/requires.txt +GATr.egg-info/top_level.txt +gatr/__init__.py +gatr/baselines/__init__.py +gatr/baselines/gcan.py +gatr/baselines/mlp.py +gatr/baselines/segnn.py +gatr/baselines/transformer.py +gatr/experiments/__init__.py +gatr/experiments/base_experiment.py +gatr/experiments/base_wrapper.py +gatr/experiments/arteries/__init__.py +gatr/experiments/arteries/dataset.py +gatr/experiments/arteries/experiment.py +gatr/experiments/arteries/wrappers.py +gatr/experiments/nbody/__init__.py +gatr/experiments/nbody/dataset.py +gatr/experiments/nbody/experiment.py +gatr/experiments/nbody/simulator.py +gatr/experiments/nbody/wrappers.py +gatr/interface/__init__.py +gatr/interface/object.py +gatr/interface/plane.py +gatr/interface/point.py +gatr/interface/pseudoscalar.py +gatr/interface/reflection.py +gatr/interface/rotation.py +gatr/interface/scalar.py +gatr/interface/translation.py +gatr/layers/__init__.py +gatr/layers/dropout.py +gatr/layers/gatr_block.py +gatr/layers/layer_norm.py +gatr/layers/linear.py +gatr/layers/attention/__init__.py +gatr/layers/attention/attention.py +gatr/layers/attention/config.py +gatr/layers/attention/positional_encoding.py +gatr/layers/attention/qkv.py +gatr/layers/attention/self_attention.py +gatr/layers/mlp/__init__.py +gatr/layers/mlp/config.py +gatr/layers/mlp/geometric_bilinears.py +gatr/layers/mlp/mlp.py +gatr/layers/mlp/nonlinearities.py +gatr/nets/__init__.py +gatr/nets/axial_gatr.py +gatr/nets/gatr.py +gatr/primitives/__init__.py +gatr/primitives/attention.py +gatr/primitives/bilinear.py +gatr/primitives/dropout.py +gatr/primitives/dual.py +gatr/primitives/invariants.py +gatr/primitives/linear.py +gatr/primitives/nonlinearities.py +gatr/primitives/normalization.py +gatr/primitives/data/geometric_product.pt +gatr/primitives/data/outer_product.pt +gatr/utils/__init__.py +gatr/utils/clifford.py +gatr/utils/compile_linear.py +gatr/utils/dual_basis.py +gatr/utils/einsum.py +gatr/utils/logger.py +gatr/utils/misc.py +gatr/utils/mlflow.py +gatr/utils/plotting.py +gatr/utils/quaternions.py +gatr/utils/tensors.py +scripts/artery_experiment.py +scripts/generate_nbody_dataset.py +scripts/nbody_experiment.py \ No newline at end of file diff --git a/gafl/build/geometric-algebra-transformer/GATr.egg-info/dependency_links.txt b/gafl/build/geometric-algebra-transformer/GATr.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/GATr.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/gafl/build/geometric-algebra-transformer/GATr.egg-info/requires.txt b/gafl/build/geometric-algebra-transformer/GATr.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6a72a6ffd5695d0dead9a142412acc8a772e8e0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/GATr.egg-info/requires.txt @@ -0,0 +1,5 @@ +einops +numpy<1.25 +opt_einsum @ git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10 +torch>=2.0 +xformers diff --git a/gafl/build/geometric-algebra-transformer/GATr.egg-info/top_level.txt b/gafl/build/geometric-algebra-transformer/GATr.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4556fc73f387795f71f0d8839846860923ca0143 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/GATr.egg-info/top_level.txt @@ -0,0 +1 @@ +gatr diff --git a/gafl/build/geometric-algebra-transformer/LICENSE b/gafl/build/geometric-algebra-transformer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5e0aaa267c75621466ee8e22ac6bdeeaa61ca607 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2023 Qualcomm Technologies, Inc. + +All rights reserved. + +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: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer: + +* 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. + +* 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. + +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. diff --git a/gafl/build/geometric-algebra-transformer/README.md b/gafl/build/geometric-algebra-transformer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5866da9aaacb754f5096b86f922d187781bb1fbb --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/README.md @@ -0,0 +1,394 @@ +# Geometric Algebra Transformers + +This repository contains the official implementation of the +[**Geometric Algebra Transformer**](https://arxiv.org/abs/2305.18415) by +[Johann Brehmer](mailto:jbrehmer@qti.qualcomm.com), Pim de Haan, Sönke Behrends, and Taco Cohen, +published at NeurIPS 2023. + +![GATr = geometric algebra representations + equivariant layers + Transformer architecture](img/gatr.png) + +## 1. Abstract + +Problems involving geometric data arise in physics, chemistry, robotics, computer vision, and many +other fields. Such data can take numerous forms, such as points, direction vectors, translations, or +rotations, but to date there is no single architecture that can be applied to such a wide variety of +geometric types while respecting their symmetries. In this paper we introduce the Geometric Algebra +Transformer (GATr), a general-purpose architecture for geometric data. GATr represents inputs, +outputs, and hidden states in the projective geometric (or Clifford) algebra, which offers an +efficient 16-dimensional vector-space representation of common geometric objects as well as +operators acting on them. GATr is equivariant with respect to E(3), the symmetry group of 3D +Euclidean space. As a Transformer, GATr is versatile, efficient, and scalable. We demonstrate GATr +in problems from n-body modeling to wall-shear-stress estimation on large arterial meshes to robotic +motion planning. GATr consistently outperforms both non-geometric and equivariant baselines in terms +of error, data efficiency, and scalability. + +## 2. Getting started + +Clone the repository. + +```bash +git clone https://github.com/Qualcomm-AI-research/geometric-algebra-transformer +``` + +Build the Docker image from inside the checked-out repository. On Linux, this can be done using + +```bash +cd geometric-algebra-transformer +docker build -f docker/Dockerfile --tag gatr:latest . +``` + +The commands for Windows are similar. + +Once the image has built successfully, we can run a container that is based on it. + +On Linux, the command that does this and also + +- mounts the current working directory into the container +- changes to the current working directory +- exposes all of the host's GPUs in the container + +is + +```bash +docker run --rm -it -v $PWD:$PWD -w $PWD --gpus=all gatr:latest /bin/bash +``` + +## 3. Running experiments + +In this repository, we include two experiments: one on a synthetic n-body modeling problem and one +on predicting the wall shear stress on artery walls. + +Running experiments will require the specification of directories for datasets, checkpoints, and +logs. We will define a common base directory (feel free to adapt): + +```bash +BASEDIR=/tmp/gatr-experiments +``` + +### n-body modeling + +First, we need to generate training and evaluation datasets: + +```bash +python scripts/generate_nbody_dataset.py base_dir="${BASEDIR}" seed=42 +``` + +Let's train a GATr model, using just 1000 (or 1%) training trajectories and training for 5000 steps: + +```bash +python scripts/nbody_experiment.py base_dir="${BASEDIR}" seed=42 model=gatr_nbody data.subsample=0.01 training.steps=5000 run_name=gatr +``` + +At the end of the training, evaluation metrics are printed to stdout +and written to `$BASEDIR/experiments/nbody/gatr/metrics`. Training and evaluation are also +tracked with MLflow to an SQLite database at `$BASEDIR/tracking/mlflow.db`. +MLFlow is configured in the `mlflow` section of `config/nbody.yaml`. + +We can repeat the same for different baselines, for instance: + +```bash +for METHOD in mlp transformer gcagnn se3transformer segnn +do + python scripts/nbody_experiment.py base_dir="${BASEDIR}" seed=42 model=${METHOD}_nbody data.subsample=0.01 training.steps=5000 run_name=$METHOD +done +``` + +On the `eval` set (without domain shift), you should get results like these: + +```text + Method | MSE +----------------+-------- + GATr | 0.0005 +----------------+-------- + MLP | 0.0776 + Transformer | 0.0050 + GCA-GNN | 0.0526 +SE3-Transformer | 0.0025 + SEGNN | 0.0006 +``` + +Note that the code is +[not fully deterministic](https://pytorch.org/docs/stable/notes/randomness.html), so you will not +get these exact numbers. (After averaging over multiple seeds, such fluctuations should be +negligible). + +You can also vary the number of training samples seen (`data.subsample`), the number of optimizer +steps (`training.steps`), the random seed (`seed`), and many other settings. Have a look at +[the n-body config](config/nbody.yaml) and [the GATr model config](config/model/gatr_nbody.yaml). + +If you train for long enough and average results from multiple random seeds, you should get numbers +that are comparable to Fig. 2 in our paper. However, do not expect exact reproducibility: the paper +experiments were performed with an earlier version of GATr than the one published in this +repository. In addition, there is stochasticity both in the dataset generation and in the +initialization and training of the networks. + +### Arterial wall-shear-stress estimation + +The arterial wall-shear-stress experiment uses a dataset created by +[Julian Suk et al](https://arxiv.org/abs/2212.05023). + +First, you need to download that dataset following +[the instructions in their repo](https://github.com/sukjulian/coronary-mesh-convolution#data). +We only need the single (not bifurcating) dataset. Store this dataset at some location +`$ARTERYDIR/raw/database.hdf5` and set the environment variable `$ARTERYDIR` correspondingly +(as we will use it in the commands below). + +To train a GATr model on a non-canonicalized version of this dataset for 20k steps, run: + +```shell +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 +``` + +To train a Transformer baseline, run: + +```shell +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 +``` + +Eventually you should find results like these: + +```text + Method | Approximation error +-------------+--------------------- + GATr | 0.089 + Transformer | 0.105 +``` + +If you run for long enough, you should get results comparable to Fig. 3 and Tbl. 2 in our paper. +Similar to the nbody experiment, results are also tracked with MLFlow. +Again, there is no guarantee for exact reproducibility due to code changes and stochasticity. + +## 4. Using GATr + +To use GATr on your own problem, you will at least need two components from this repository: +GATr networks, which act on multivector data, and interface functions that embed various geometric +objects into this multivector representations. + +Here is an example code snippet that illustrates the recipe: + +```python +from gatr import GATr, SelfAttentionConfig, MLPConfig +from gatr.interface import embed_point, extract_scalar +import torch + + +class ExampleWrapper(torch.nn.Module): + """Example wrapper around a GATr model. + + Expects input data that consists of a point cloud: one 3D point for each item in the data. + Returns outputs that consists of one scalar number for the whole dataset. + + Parameters + ---------- + blocks : int + Number of transformer blocks + hidden_mv_channels : int + Number of hidden multivector channels + hidden_s_channels : int + Number of hidden scalar channels + """ + + def __init__(self, blocks=20, hidden_mv_channels=16, hidden_s_channels=32): + super().__init__() + self.gatr = GATr( + in_mv_channels=1, + out_mv_channels=1, + hidden_mv_channels=hidden_mv_channels, + in_s_channels=None, + out_s_channels=None, + hidden_s_channels=hidden_s_channels, + num_blocks=blocks, + attention=SelfAttentionConfig(), # Use default parameters for attention + mlp=MLPConfig(), # Use default parameters for MLP + ) + + def forward(self, inputs): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor with shape (*batch_dimensions, num_points, 3) + Point cloud input data + + Returns + ------- + outputs : torch.Tensor with shape (*batch_dimensions, 1) + Model prediction: a single scalar for the whole point cloud. + """ + + # Embed point cloud in PGA + embedded_inputs = embed_point(inputs).unsqueeze(-2) # (..., num_points, 1, 16) + + # Pass data through GATr + embedded_outputs, _ = self.gatr(embedded_inputs, scalars=None) # (..., num_points, 1, 16) + + # Extract scalar and aggregate outputs from point cloud + nodewise_outputs = extract_scalar(embedded_outputs) # (..., num_points, 1, 1) + outputs = torch.mean(nodewise_outputs, dim=(-3, -2)) # (..., 1) + + return outputs +``` + +In the following, we will go into more detail on the conventions used in this code base and the +structure of the repository. + +### Design choices + +**Representations**: GATr operates with two kind of representations: geometric algebra multivectors +and auxiliary scalar representations. Both are simply represented as `torch.Tensor` instances. + +The multivectors are based on the projective geometric algebra G(3, 0, 1). They are tensors of the +shape `(..., 16)`, for instance `(batchsize, items, channels, 16)`. The sixteen multivector +components are sorted as in the +[`clifford` library](https://clifford.readthedocs.io/en/latest/), as follows: +`[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, +x_0123]`. + +Scalar representations have free shapes, but should match the multivector representations they +accompany in batchsize and number of items. The number of channels may be different. + +**Interface to the real world**: To map the multivector representations to physical objects, we +use the plane-based convention presented in +[Roelfs and De Keninck, "Graded symmetry groups: Plane and simple"](https://arxiv.org/abs/2107.03771). +3D points are thus represented as trivectors, planes as vectors, and so on. We provide these +these interface functions in the `gatr.interface` submodule. + +**Functions**: We distinguish between primitives (functions) and layers (often stateful +`torch.nn.Module` instances). Almost all primitives and layers are Pin(3, 0, 1)-equivariant, +see docstrings for exceptions. + +### Repository structure + +```text +geometric-algebra-transformer +| +└───config: configuration YAML files for the experiments +| └───model: model configurations +| | arteries.yaml: default configuration for the artery experiment +| | hydra.yaml: hydra configuration (imported by the experiment configs) +| | nbody.yaml: default configuration for the n-body experiment +| +└───docker: Docker environment +| └───ext_packages: patches for external dependencies +| | Dockerfile: Docker container specification +| | requirements.txt: external dependencies installed in Dockerfile +| +└───gatr: core library +| └───baselines: baseline layers and architectures +| | | gcan.py: GCA-MLP and GCA-GNN baselines +| | | mlp.py: MLP baseline +| | | segnn.py: SEGNN baseline +| | | transformer.py: Transformer baseline +| | +| └───experiments: experiment managers +| | └───arteries: experiment manager, wrappers, etc for the artery experiment +| | └───nbody: experiment manager, wrappers, etc for the n-body experiment +| | | base_experiment.py: base class for experiment managers +| | | base_wrapper.py: base class for experiment-specific GATr wrappers +| | +| └───interface: embedding of geometric quantities into projective geometric algebra +| | | object.py: 3D objects consisting of positions and orientations +| | | plane.py: planes +| | | point.py: points +| | | pseudoscalar.py: pseudoscalars +| | | reflection.py: planar reflections +| | | rotation.py: rotations +| | | scalar.py: scalars +| | | translation.py: translations +| | +| └───layers: network layers +| | └───attention: self-attention layer, its components, and the corresponding configuration +| | └───mlp: geometric MLP, its components, and the corresponding configuration +| | | dropout.py: multivector dropout +| | | gatr_block.py: GATr transformer block, the main layer that GATr networks consist of +| | | layer_norm.py: geometric LayerNorm +| | | linear.py: equivariant linear layer between multivectors +| | +| └───nets: complete network architectures +| | | axial_gatr.py: axial-attention version of GATr for two token dimensions +| | | gatr.py: GATr architecture for a single token dimension +| | +| └───primitives: core functional building blocks of GATr +| | └───data: pre-computed basis stored in `.pt` files +| | | attention.py: geometric attention mechanism +| | | bilinear.py: bilinear equivariant functions like the geometric product +| | | dropout.py: geometric dropout +| | | dual.py: dual-related functions like the equivariant join +| | | invariants.py: invariant functions of multivectors like the norm +| | | linear.py: equivariant linear maps between multivectors +| | | nonlinearities.py: gated nonlinearities +| | | normalization.py: geometric normalization functions +| | +| └───utils: utility functions +| | clifford.py: non-differentiable GA functions based on the clifford library +| | dual_basis.py: helper functions to construct the equivariant join efficiently +| | einsum.py: optimized einsum function +| | logger.py: logger +| | misc.py: various utility functions +| | mlflow.py: logging with MLflow +| | plotting.py: plotting defaults +| | quaternions.py: quaternion operations +| | tensors.py: various tensor operations +| +└───scripts: entrypoints to run experiments +| | artery_experiment.py: artery experiment script +| | generate_nbody_dataset.py: data generation script for the n-body experiment +| | nbody_experiment.py: n-body experiment script +│ +└───tests: unit tests (e.g. for self-consistency and Pin equivariance) +| └───gatr +| | └───baselines: unit tests for gatr.baselines +| | └───interface: unit tests for gatr.interface +| | └───layers: unit tests for gatr.layers +| | └───nets: unit tests for gatr.nets +| | └───primitives: unit tests for gatr.primitives +| | └───utils: unit tests for gatr.utils +| | +| └───helpers: utility functions for unit tests +| | constants.py: test settings (like tolerances) +| | equivariance.py: helper functions to test Pin equivariance +| | geometric_algebra.py: helper functions to test GA functionality +│ +└───tests_regression: regression tests (training a GATr to predict the distance between points) +│ +| .coveragerc: coverage configuration +| .dockerignore: Docker configuration +| .gitignore: git configuration +│ .pylintrc: pylint configuration +│ LICENSE: license under which this code may be used +│ pyproject.toml: project settings +│ README.md: this README file +│ setup.py: installation script +``` + +## 5. Other geometric algebras + +The GATr paper and this repository use the projective geometric algebra. In the work +[Euclidean, Projective, Conformal: Choosing a Geometric Algebra for Equivariant Transformers](https://arxiv.org/abs/2311.04744), +we explored using the Euclidean and conformal algebras instead. We found a nuanced trade-off +between the different algebras for their use in GATr. At the moment, the code for the different +algebras has not been released. + +## 6. Citation + +If you find our code useful, please cite: + +```text +@inproceedings{brehmer2023geometric, + title = {Geometric Algebra Transformer}, + author = {Brehmer, Johann and de Haan, Pim and Behrends, S{\"o}nke and Cohen, Taco}, + booktitle = {Advances in Neural Information Processing Systems}, + year = {2023}, + volume = {37}, + eprint = {2305.18415}, + url = {https://arxiv.org/abs/2305.18415}, +} + +@inproceedings{dehaan2023euclidean, + title={Euclidean, Projective, Conformal: Choosing a Geometric Algebra for Equivariant Transformers}, + author={Pim de Haan and Taco Cohen and Johann Brehmer}, + booktitle = {Proceedings of The 27th International Conference on Artificial Intelligence and Statistics}, + year={2024}, + url = {https://arxiv.org/abs/2311.04744}, +} +``` diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9604b1ea4d331d71d67f39178103f1b945a00f28 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .layers.attention.config import SelfAttentionConfig +from .layers.mlp.config import MLPConfig +from .nets.axial_gatr import AxialGATr +from .nets.gatr import GATr + +__version__ = "1.2.0" diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e91f2baca0662b6b197402d5875aa799837dc855 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .mlp import MLP +from .transformer import BaselineAxialTransformer, BaselineTransformer diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/gcan.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/gcan.py new file mode 100644 index 0000000000000000000000000000000000000000..b9efe3eadedfcd2124c74b2021a570cf56587d54 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/gcan.py @@ -0,0 +1,299 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from code by David Ruhe. + +MIT License + +Copyright (c) Microsoft Corporation. + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +import numpy as np +import torch +from cliffordlayers.cliffordalgebra import CliffordAlgebra +from cliffordlayers.nn.modules.gcan import MultiVectorAct, PGAConjugateLinear +from torch import nn +from torch_geometric.nn import MessagePassing + + +class GCAMLP(nn.Module): + """GCA-MLP model. + + As described in D. Ruhe et al, "Geometric Clifford Algebra Networks". + Based on layers from the official + [cliffordlayers code](https://github.com/microsoft/cliffordlayers/tree/main). + + This network uses the same projective geometric algebra representations as GATr, but is not + E(3)-equivariant. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_shape : tuple of int + Shape expected of input tensors, excluding the 16 components of the multivectors. + out_shape : tuple of int + Shape expected for output tensors, excluding the 16 components of the multivectors. + hidden_channels : int + Number of hidden channels. + hidden_layers : int + Number of hidden layers. + act_agg : {"linear", "sum", "mean"} + Aggregation function. + flatten : bool + If True, the network flattens the input along all dimensions except the first (batch) + and last (multivector component) dimension. Otherwise, all dimensions except for the last + two are treated as batch dimensions. + """ + + def __init__( + self, + in_shape, + out_shape, + hidden_channels, + hidden_layers, + act_agg="linear", + flatten=True, + **kwargs, + ): + super().__init__() + + if not hidden_layers > 0: + raise NotImplementedError("Only supports > 0 hidden layers") + + in_channels = np.product(in_shape) if flatten else in_shape[-1] + out_channels = np.product(out_shape) if flatten else out_shape[-1] + self.flatten = flatten + self.in_shape = in_shape + self.out_shape = out_shape + + self.pga = CliffordAlgebra((0, 1, 1, 1)) + self.model = self._make_net( + in_channels, out_channels, hidden_channels, hidden_layers, act_agg + ) + + def _make_net(self, in_channels, out_channels, hidden_channels, hidden_layers, act_agg): + """PGA-MLP code as sent by David Ruhe.""" + + all_blades = list(range(16)) + action_blades = (0, 5, 6, 7, 8, 9, 10, 15) # From David; using all blades results in NaNs + + linear_in = PGAConjugateLinear( + in_channels, + hidden_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ) + linear_out = nn.Sequential( + MultiVectorAct( + hidden_channels, + self.pga, + input_blades=all_blades, + agg=act_agg, + ), + PGAConjugateLinear( + hidden_channels, + out_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ), + ) + mlp = [ + nn.Sequential( + MultiVectorAct( + hidden_channels, + self.pga, + input_blades=all_blades, + agg=act_agg, + ), + PGAConjugateLinear( + hidden_channels, + hidden_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ), + ) + for _ in range(hidden_layers - 1) + ] + return nn.Sequential(linear_in, *mlp, linear_out) + + def forward(self, inputs: torch.Tensor): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor with shape (..., 16) + Input multivectors. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivectors. + """ + input_shape = inputs.shape + if self.flatten: + # Flatten all non-batch dimensions + inputs = inputs.reshape(input_shape[0], -1, 16) + outputs = self.model(inputs) + if self.flatten: + outputs = outputs.reshape(input_shape[0], *self.out_shape, 16) + return outputs + + +class GCAGNNLayer(MessagePassing): # pylint: disable=abstract-method + """GCA-GNN layer as described in D. Ruhe et al. + + This was described in "Geometric Clifford Algebra Networks" by D. Ruhe et. al, + and in private communication from D. Ruhe. + Uses the GCAN layers in the official cliffordlayers library, pieces them together based on the + information in the paper. Follows the PyG message-passing schema. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + message_channels : int + Number of channels in the messages. + mlp_hidden_channels : int + Number of hidden channels in the MLPs. + mlp_hidden_layers : int + Number of hidden layers in the MLPs. + """ + + def __init__( + self, + in_channels, + out_channels, + message_channels, + mlp_hidden_channels, + mlp_hidden_layers, + ): + super().__init__(aggr="add", flow="source_to_target", node_dim=-3) + + # GCA-MLPs for input, output, message, and update functions + shared_kwargs = dict( + hidden_channels=mlp_hidden_channels, hidden_layers=mlp_hidden_layers, flatten=False + ) + self.message_mlp = GCAMLP((2 * in_channels,), (message_channels,), **shared_kwargs) + self.update_mlp = GCAMLP( + (in_channels + message_channels,), (out_channels,), **shared_kwargs + ) + + def forward(self, x, edge_index): # pylint: disable=arguments-differ + """Forward pass.""" + return self.propagate(edge_index, x=x) + + def message(self, x_i, x_j): # pylint: disable=arguments-differ + """Constructs message.""" + features = torch.cat([x_i, x_j], dim=1) # shape (edges, 2*node_channels, 16) + message = self.message_mlp(features) # shape (edges, message_channels, 16) + return message + + def update(self, aggr_out, x): # pylint: disable=arguments-differ + """Updates node states with aggregated messages.""" + + features = torch.cat( + [x, aggr_out], dim=1 + ) # shape (nodes, node_channels + message_channels, 16) + x = self.update_mlp(features) # shape (nodes, node_channels, 16) + return x + + +class GCAGNN(nn.Module): + """GCA-GNN model as described in D. Ruhe et al. + + The model was described in "Geometric Clifford Algebra Networks" by D.Ruhe et al., + and in private communication from D. Ruhe. + + Combines multiple GCAGNNLayers. + + This network uses the same projective geometric algebra representations as GATr, but is not + E(3)-equivariant. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + node_channels : int + Number of channels in the hidden representation for each node. + message_channels : int + Number of channels in the messages. + mlp_hidden_channels : int + Number of hidden channels in the MLPs. + mlp_hidden_layers : int + Number of hidden layers in the MLPs. + message_passing_steps : int + Number of message-passing steps / GCAGNNLayer blocks. + """ + + def __init__( + self, + in_channels, + out_channels, + node_channels, + message_channels, + mlp_hidden_channels, + mlp_hidden_layers, + message_passing_steps, + **kwargs, + ): + super().__init__() + + # Construct layers + self.layers = nn.ModuleList([]) + shared_kwargs = dict( + mlp_hidden_channels=mlp_hidden_channels, + mlp_hidden_layers=mlp_hidden_layers, + message_channels=message_channels, + ) + + # Initial step: in_channels to node_channels + self.layers.append(GCAGNNLayer(in_channels, node_channels, **shared_kwargs)) + + # Intermediate steps / layers + for _ in range(message_passing_steps - 2): + self.layers.append(GCAGNNLayer(node_channels, node_channels, **shared_kwargs)) + + # Final step: node_channels to out_channels + self.layers.append(GCAGNNLayer(node_channels, out_channels, **shared_kwargs)) + + def forward(self, x, edge_index): + """Forward pass.""" + for layer in self.layers: + x = layer(x, edge_index=edge_index) + return x diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/mlp.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..489973d86bd4165453148998d2985ed97e11cc0f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/mlp.py @@ -0,0 +1,40 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import List + +import numpy as np +import torch +from torch import nn + + +class MLP(nn.Module): + """A simple baseline MLP. + + Flattens all dimensions except batch and uses GELU nonlinearities. + """ + + def __init__(self, in_shape, out_shape, hidden_channels, hidden_layers): + super().__init__() + + if not hidden_layers > 0: + raise NotImplementedError("Only supports > 0 hidden layers") + + self.in_shape = in_shape + self.out_shape = out_shape + + layers: List[nn.Module] = [nn.Linear(np.product(in_shape), hidden_channels)] + for _ in range(hidden_layers - 1): + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_channels, hidden_channels)) + + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_channels, np.product(self.out_shape))) + self.mlp = nn.Sequential(*layers) + + def forward(self, inputs: torch.Tensor): + """Forward pass of baseline MLP.""" + batchsize = inputs.shape[0] + inputs = inputs.reshape(batchsize, -1) + outputs = self.mlp(inputs) + outputs = outputs.reshape(batchsize, *self.out_shape) + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/segnn.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/segnn.py new file mode 100644 index 0000000000000000000000000000000000000000..dcffd7dafcf50c8eacfd40b9304181cab7e7e607 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/segnn.py @@ -0,0 +1,110 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/RobDHess/Steerable-E3-GNN/blob/1b95898f6f18204b510ae127d7f38cd29f610f4d/nbody/train_nbody.py +by Johannes Brandstetter, Rob Hesselink, Erik Bekkers at +https://github.com/RobDHess/Steerable-E3-GNN + +MIT License + +Copyright (c) 2021 Johannes Brandstetter, Rob Hesselink, Erik Bekkers + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +from e3nn.o3 import Irreps +from segnn.balanced_irreps import BalancedIrreps, WeightBalancedIrreps +from segnn.segnn.segnn import SEGNN +from torch import nn + + +def _make_segnn_irreps(vec_channels, scalar_channels): + """Creates an Irreps object for SEGNNModel given a number of O(3) vectors and scalars.""" + assert vec_channels > 0 or scalar_channels > 0 + irreps = [] + if vec_channels > 0: + irreps.append(f"{vec_channels}x1o") + if scalar_channels > 0: + irreps.append(f"{scalar_channels}x0e") + return Irreps(" + ".join(irreps)) + + +class SEGNNModel(nn.Module): + """SEGNN baseline. + + We restrict ourselves to vector and scalar inputs, as those were sufficient for our experiments. + + References + ---------- + J. Brandstetter et al, "Geometric and Physical Quantities Improve E(3) Equivariant Message + Passing", ICLR 2022 + """ + + def __init__( + self, + input_vec_channels=2, + input_s_channels=1, + output_vec_channels=1, + output_s_channels=0, + additional_message_s_channels=2, + hidden_features=128, + lmax_h=2, + lmax_attr=3, + subspace_type="weightbalanced", + layers=7, + norm="instance", + pool="avg", + task="node", + **kwargs, + ): + super().__init__() + + input_irreps = _make_segnn_irreps(input_vec_channels, input_s_channels) + output_irreps = _make_segnn_irreps(output_vec_channels, output_s_channels) + edge_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + node_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + additional_message_irreps = _make_segnn_irreps(0, additional_message_s_channels) + + if subspace_type == "weightbalanced": + hidden_irreps = WeightBalancedIrreps( + _make_segnn_irreps(0, hidden_features), node_attr_irreps, sh=True, lmax=lmax_h + ) + elif subspace_type == "balanced": + hidden_irreps = BalancedIrreps(lmax_h, hidden_features, True) + else: + raise ValueError(f"Unknown subspace type {subspace_type}") + + self.model = SEGNN( + input_irreps, + hidden_irreps, + output_irreps, + edge_attr_irreps, + node_attr_irreps, + num_layers=layers, + norm=norm, + pool=pool, + task=task, + additional_message_irreps=additional_message_irreps, + ) + + def forward(self, *inputs, **kwargs): + """Forward pass.""" + return self.model(*inputs, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/transformer.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..072e5b86e59d89c00889697f96e59eaba8b3210e --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/baselines/transformer.py @@ -0,0 +1,557 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Baseline transformer.""" + +from functools import partial +from typing import Optional, Tuple + +import torch +from einops import rearrange +from torch import nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers import ApplyRotaryPositionalEncoding +from gatr.primitives.attention import scaled_dot_product_attention +from gatr.utils.tensors import to_nd + +# Default rearrange patterns for odd blocks +_REARRANGE_PATTERN = "... i j c -> ... j i c" + + +class BaselineLayerNorm(nn.Module): + """Baseline layer norm over all dimensions except the first.""" + + @staticmethod + def forward(inputs: torch.Tensor) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + + Returns + ------- + outputs : Tensor + Normalized inputs. + """ + return torch.nn.functional.layer_norm(inputs, normalized_shape=inputs.shape[1:]) + + +class MultiHeadQKVLinear(nn.Module): + """Compute queries, keys, and values via multi-head attention. + + Parameters + ---------- + in_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + """ + + def __init__(self, in_channels, hidden_channels, num_heads): + super().__init__() + self.num_heads = num_heads + self.linear = nn.Linear(in_channels, 3 * hidden_channels * num_heads) + + def forward(self, inputs): + """Forward pass. + + Returns + ------- + q : Tensor + Queries + k : Tensor + Keys + v : Tensor + Values + """ + qkv = self.linear(inputs) # (..., num_items, 3 * hidden_channels * num_heads) + q, k, v = rearrange( + qkv, + "... items (qkv hidden_channels num_heads) -> qkv ... num_heads items hidden_channels", + num_heads=self.num_heads, + qkv=3, + ) + return q, k, v + + +class MultiQueryQKVLinear(nn.Module): + """Compute queries, keys, and values via multi-query attention. + + Parameters + ---------- + in_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + """ + + def __init__(self, in_channels, hidden_channels, num_heads): + super().__init__() + self.num_heads = num_heads + self.q_linear = nn.Linear(in_channels, hidden_channels * num_heads) + self.k_linear = nn.Linear(in_channels, hidden_channels) + self.v_linear = nn.Linear(in_channels, hidden_channels) + + def forward(self, inputs): + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + + Returns + ------- + q : Tensor + Queries + k : Tensor + Keys + v : Tensor + Values + """ + q = rearrange( + self.q_linear(inputs), + "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels", + num_heads=self.num_heads, + ) + k = self.k_linear(inputs)[..., None, :, :] # (..., head=1, item, hidden_channels) + v = self.v_linear(inputs)[..., None, :, :] + return q, k, v + + +class BaselineSelfAttention(nn.Module): + """Baseline self-attention layer. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_enc_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_heads: int = 8, + pos_encoding: bool = False, + pos_enc_base: int = 4096, + multi_query: bool = True, + ) -> None: + super().__init__() + + # Store settings + self.num_heads = num_heads + self.hidden_channels = hidden_channels + + # Linear maps + qkv_class = MultiQueryQKVLinear if multi_query else MultiHeadQKVLinear + self.qkv_linear = qkv_class(in_channels, hidden_channels, num_heads) + self.out_linear = nn.Linear(hidden_channels * num_heads, out_channels) + + # Optional positional encoding + if pos_encoding: + self.pos_encoding = ApplyRotaryPositionalEncoding( + hidden_channels, item_dim=-2, base=pos_enc_base + ) + else: + self.pos_encoding = None + + def forward( + self, inputs: torch.Tensor, attention_mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor + Outputs + """ + q, k, v = self.qkv_linear(inputs) # each: (..., num_heads, num_items, num_channels, 16) + + # Rotary positional encoding + if self.pos_encoding is not None: + q = self.pos_encoding(q) + k = self.pos_encoding(k) + + # Attention layer + h = self._attend(q, k, v, attention_mask) + + # Concatenate heads and transform linearly + h = rearrange( + h, + "... num_heads num_items hidden_channels -> ... num_items (num_heads hidden_channels)", + ) + outputs = self.out_linear(h) # (..., num_items, out_channels) + + return outputs + + @staticmethod + def _attend(q, k, v, attention_mask=None): + """Scaled dot-product attention.""" + + # Add batch dimension if needed + bh_shape = q.shape[:-2] + q = to_nd(q, 4) + k = to_nd(k, 4) + v = to_nd(v, 4) + + # SDPA + outputs = scaled_dot_product_attention( + q.contiguous(), k.expand_as(q).contiguous(), v.expand_as(q), attn_mask=attention_mask + ) + + # Return batch dimensions to inputs + outputs = outputs.view(*bh_shape, *outputs.shape[-2:]) + + return outputs + + +class BaselineTransformerBlock(nn.Module): + """Baseline transformer block. + + Inputs are first processed by a block consisting of LayerNorm, multi-head self-attention, and + residual connection. Then the data is processed by a block consisting of another LayerNorm, an + item-wise two-layer MLP with GeLU activations, and another residual connection. + + Parameters + ---------- + channels : int + Number of input and output channels. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + increase_hidden_channels : int + Factor by which the key, query, and value size is increased over the default value of + hidden_channels / num_heads. + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + channels, + num_heads: int = 8, + pos_encoding: bool = False, + pos_encoding_base: int = 4096, + increase_hidden_channels=1, + multi_query: bool = True, + ) -> None: + super().__init__() + + self.norm = BaselineLayerNorm() + + # When using positional encoding, the number of scalar hidden channels needs to be even. + # It also should not be too small. + hidden_channels = channels // num_heads * increase_hidden_channels + if pos_encoding: + hidden_channels = (hidden_channels + 1) // 2 * 2 + hidden_channels = max(hidden_channels, 16) + + self.attention = BaselineSelfAttention( + channels, + channels, + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encoding, + pos_enc_base=pos_encoding_base, + multi_query=multi_query, + ) + + self.mlp = nn.Sequential( + nn.Linear(channels, 2 * channels), + nn.GELU(), + nn.Linear(2 * channels, channels), + ) + + def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor + Outputs + """ + + # Residual attention + h = self.norm(inputs) + h = self.attention(h, attention_mask) + outputs = inputs + h + + # Residual MLP + h = self.norm(outputs) + h = self.mlp(h) + outputs = outputs + h + + return outputs + + +class BaselineTransformer(nn.Module): + """Baseline transformer. + + Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an + MLP, residual connections, and normalization layers. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + hidden_channels : int + Number of hidden channels. + num_blocks : int + Number of transformer blocks. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + increase_hidden_channels : int + Factor by which the key, query, and value size is increased over the default value of + hidden_channels / num_heads. + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_blocks: int = 10, + num_heads: int = 8, + pos_encoding: bool = False, + pos_encoding_base: int = 4096, + checkpoint_blocks: bool = False, + increase_hidden_channels=1, + multi_query: bool = False, + ) -> None: + super().__init__() + self.checkpoint_blocks = checkpoint_blocks + self.linear_in = nn.Linear(in_channels, hidden_channels) + self.blocks = nn.ModuleList( + [ + BaselineTransformerBlock( + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encoding, + pos_encoding_base=pos_encoding_base, + increase_hidden_channels=increase_hidden_channels, + multi_query=multi_query, + ) + for _ in range(num_blocks) + ] + ) + self.linear_out = nn.Linear(hidden_channels, out_channels) + + def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor with shape (..., num_items, num_channels) + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor with shape (..., num_items, num_channels) + Outputs + """ + h = self.linear_in(inputs) + for block in self.blocks: + if self.checkpoint_blocks: + fn = partial(block, attention_mask=attention_mask) + h = checkpoint(fn, h) + else: + h = block(h, attention_mask=attention_mask) + outputs = self.linear_out(h) + return outputs + + +class BaselineAxialTransformer(nn.Module): + """Baseline axial transformer for data with two token dimensions. + + Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an + MLP, residual connections, and normalization layers. + + Assumes input data with shape `(..., num_items_1, num_items_2, num_channels, [16])`. + + The first, third, fifth, ... block computes attention over the `items_2` axis. The other blocks + compute attention over the `items_1` axis. Positional encoding can be specified separately for + both axes. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + hidden_channels : int + Number of hidden channels. + num_blocks : int + Number of transformer blocks. + num_heads : int + Number of attention heads. + pos_encodings : tuple of bool + Whether to apply rotary positional embeddings along the item dimensions to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + collapse_dims : tuple of bool + Whether batch and token dimensions will be collapsed to support xformers block attention. + The first element of this tuple describes the behaviour in the 0th, 2nd, ... block, the + second element in the 1st, 3rd, ... block (where the axes are reversed). + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_blocks: int = 20, + num_heads: int = 8, + pos_encodings: Tuple[bool, bool] = (False, False), + pos_encoding_base: int = 4096, + collapse_dims: Tuple[bool, bool] = (False, False), + ) -> None: + super().__init__() + self.linear_in = nn.Linear(in_channels, hidden_channels) + self.blocks = nn.ModuleList( + [ + BaselineTransformerBlock( + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encodings[(block + 1) % 2], + pos_encoding_base=pos_encoding_base, + ) + for block in range(num_blocks) + ] + ) + self.linear_out = nn.Linear(hidden_channels, out_channels) + self._collapse_dims_for_even_blocks, self._collapse_dims_for_odd_blocks = collapse_dims + + def forward(self, inputs: torch.Tensor, attention_mask: Optional[Tuple] = None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor with shape (..., num_items1, num_items2, num_channels) + Input data + attention_mask : None or tuple of torch.Tensor + Optional attention masks + + Returns + ------- + outputs : Tensor with shape (..., num_items1, num_items2, num_channels) + Outputs + """ + + h = self.linear_in(inputs) + + for i, block in enumerate(self.blocks): + # For first, third, ... block, we want to perform attention over the first token + # dimension. We implement this by transposing the two item dimensions. + if i % 2 == 1: + h, input_batch_dims = self._reshape_data_before_odd_blocks(h) + else: + h, input_batch_dims = self._reshape_data_before_even_blocks(h) + + # Attention masks will also be different + if attention_mask is None: + this_attention_mask = None + else: + this_attention_mask = attention_mask[(i + 1) % 2] + + h = block(h, attention_mask=this_attention_mask) + + # Transposing back to standard axis order + if i % 2 == 1: + h = self._reshape_data_after_odd_blocks(h, input_batch_dims) + else: + h = self._reshape_data_after_even_blocks(h, input_batch_dims) + + outputs = self.linear_out(h) + + return outputs + + def _reshape_data_before_odd_blocks(self, h): + # Transpose token axes + h = rearrange(h, _REARRANGE_PATTERN) # (axis2, axis1, ...) + + # Prepare uncollapsing + input_batch_dims = h.shape[:2] + + # Collapse dimensions + if self._collapse_dims_for_odd_blocks: + h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...) + + return h, input_batch_dims + + def _reshape_data_after_odd_blocks(self, h, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_odd_blocks: + h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...) + + # Re-transpose token axes + h = rearrange(h, _REARRANGE_PATTERN) # (axis1, axis2, ...) + + return h + + def _reshape_data_before_even_blocks(self, h): + # Prepare un-collapsing + input_batch_dims = h.shape[:2] + + # Collapse + if self._collapse_dims_for_even_blocks: + h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...) + + return h, input_batch_dims + + def _reshape_data_after_even_blocks(self, h, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_even_blocks: + h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...) + + return h diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d534ef3169328c9d075fa26f053c9f6de9e1bc6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .base_experiment import BaseExperiment +from .base_wrapper import BaseWrapper diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eafe209d6241d57b778eee81e437bf1a313a970d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .dataset import InMemoryVesselDataset, NumberedVesselDataset, RotationDataset +from .experiment import ArteryExperiment +from .wrappers import ArteryBaselineWrapper, ArteryGATrWrapper diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/dataset.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc4317480743d71d6e049f0b04e4b2b57a06fdd --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/dataset.py @@ -0,0 +1,55 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import os +import re + +import numpy as np +import scipy +import torch +from coronary_mesh_convolution.datasets import InMemoryVesselDataset +from torch.utils.data import Dataset + + +class NumberedVesselDataset(InMemoryVesselDataset): + """Artery dataset with added shape id attribute.""" + + @staticmethod + def load_process_hdf5(path): + """Wrap super method with adding shape id.""" + _, sample = os.path.split(path) + data = InMemoryVesselDataset.load_process_hdf5(path) + data.shape_id = int(re.match(r"sample_(\d+)", sample).group(1)) + return data + + +class RotationDataset(Dataset): + """A dataset containing random (S)O(3) elements. + + Parameters + ---------- + num : int + Size of the dataset (number of rotations) + special : bool + If True, samples from the Haar measure on SO(3); otherwise, on O(3) + seed : int + numpy random seed + """ + + def __init__(self, num, special, seed): + super().__init__() + if special: + sampler = scipy.stats.special_ortho_group + else: + sampler = scipy.stats.ortho_group + random_state = np.random.RandomState(seed=seed) + self.data = torch.tensor( + sampler.rvs(3, size=num, random_state=random_state), dtype=torch.float32 + ) + + def __len__(self): + """Dataset size.""" + return len(self.data) + + def __getitem__(self, idx): + """Return an item from the dataset.""" + return self.data[idx] diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/experiment.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..682c60e7af6ce44deefa06f95e3280d74d5a4ac8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/experiment.py @@ -0,0 +1,259 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from pathlib import Path + +import pandas as pd +import torch +import torch_geometric +from coronary_mesh_convolution.transforms import InletGeodesics, RemoveFlowExtensions +from coronary_mesh_convolution.utils.metrics import Metrics + +from gatr.experiments import BaseExperiment +from gatr.experiments.arteries.dataset import NumberedVesselDataset, RotationDataset +from gatr.utils.logger import logger + +LABEL_SCALE = 53.8360 # the sqrt of average squared norm of training label vectors + + +class ArteryExperiment(BaseExperiment): + """Experiment manager for wall-shear-stress estimation in arteries. + + The dataset was introduced and is described in Suk et al, "Mesh Convolutional Neural Networks + for Wall Shear Stress Estimation in 3D Artery Models". + + References + ---------- + J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in + 3D Artery Models", arXiv:2109.04797 + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + super().__init__(cfg) + self._criterion = torch.nn.MSELoss() + + # Data transforms + transforms = [ + torch_geometric.transforms.GenerateMeshNormals(), + InletGeodesics(), + RemoveFlowExtensions(factor=(4.0, 1.0)), + ] + self.transform = torch_geometric.transforms.Compose(transforms) + self.rotations = RotationDataset(2000, special=False, seed=123) + + def rotate_sample(self, data): + """Rotate data sample with pre-sampled rotation matrices.""" + r = self.rotations[data.shape_id[0]] + data.pos = data.pos @ r.T + data.norm = data.norm @ r.T + data.y = data.y @ r.T + return data + + def _load_dataset(self, tag): + """Loads dataset. + + References + ---------- + J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in + 3D Artery Models", arXiv:2109.04797 + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + + # Train / validation / test splits from Suk et al + split = {"train": [0, 1600], "val": [1600, 1799], "eval": [1799, 1999]}[tag] + + if (self.cfg.data.rotate_train and tag == "train") or ( + self.cfg.data.rotate_test and tag in ["val", "eval"] + ): + transform = self.rotate_sample + else: + transform = None + + # Load dataset + dataset = NumberedVesselDataset( + Path(self.cfg.data.data_dir), + "*.hdf5", + split, + tag, + pre_transform=self.transform, + transform=transform, + ) + + # Subsample dataset if requested + if tag == "train" and self.cfg.data.subsample is not None and self.cfg.data.subsample < 1.0: + n = int(round(self.cfg.data.subsample * len(dataset))) + dataset = dataset.index_select(slice(n)) + + # Logging + logger.info(f"Loaded dataset partition {tag} with length {len(dataset)}") + + return dataset + + def _prep_data(self, data, device=None): + """Data preparation during training loop, e.g. to move data to correct device and dtype.""" + + if device is None: + device = self.device + + # Only move relevant features to GPU and float16 + data.pos = data.pos.to(device) + data.norm = data.norm.to(device) + data.geo = data.geo.to(device) + data.y = data.y.to(device) + + # NaN debugging + assert torch.all(torch.isfinite(data.pos)) + assert torch.all(torch.isfinite(data.norm)) + assert torch.all(torch.isfinite(data.geo)) + assert torch.all(torch.isfinite(data.y)) + + # Mask should also be on GPU, but remain as bool + data.mask = data.mask.to(device) + data.batch = data.batch.to(device) + + return (data,) + + def _forward(self, *data): + """Model forward pass. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + + # Forward pass + assert self.model is not None + data = data[0] + y_pred = self.model(data) + + # NaN debugging + assert torch.all(torch.isfinite(y_pred)) + + # Compute loss + y = data.y.view(*y_pred.shape) + y_normalized = y / LABEL_SCALE # normalize labels + y_pred_unnormalized = y_pred * LABEL_SCALE # unnormalize predictions + mse_normalized = self._criterion(y_pred[:, data.mask, :], y_normalized[:, data.mask, :]) + mse = self._criterion(y_pred_unnormalized[:, data.mask, :], y[:, data.mask, :]) + loss = mse_normalized + + # Additional metrics + metrics = dict(mse=mse.item(), mse_normalized=mse_normalized.item()) + + return loss, metrics + + @torch.no_grad() + def _compute_metrics(self, dataloader): + """Given a dataloader, computes all relevant metrics. To be implemented by subclasses. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Dataloader. + + Returns + ------- + metrics : dict with str keys and float values + Metrics computed from dataset. + """ + + # Move to eval mode and eval device + assert self.model is not None + self.model.eval() + eval_device = torch.device(self.cfg.training.eval_device) + self.model = self.model.to(eval_device) + + metrics_model = Metrics([dataloader]) + results = [] + + # Loop over dataset and compute metrics + for data in dataloader: + data = self._prep_data(data)[0] + model_output = self.model(data) + y_pred_batch = model_output[0] * LABEL_SCALE # Scale as ground truth, remove batch idx + num_meshes = data.batch.max() + 1 + for mesh_i in range(num_meshes): + batch_mask = data.batch == mesh_i + # Mask out one particular mesh, remove the in/outlets + prediction = y_pred_batch[batch_mask & data.mask] + label = data.y[batch_mask & data.mask] + _, maximum, mean, _ = metrics_model.absolute_differences(prediction, label) + scale_max, scale_median = metrics_model.scale(label) + approximation_error = metrics_model.approximation_error(prediction, label) + mse = self._criterion(prediction, label) + mesh_results = dict( + delta_max=maximum.item(), + delta_mean=mean.item(), + nmae=(mean / metrics_model.M).item(), + approximation_error=approximation_error.item(), + scale_max=scale_max.item(), + scale_median=scale_median.item(), + mse=mse.item(), + ) + results.append(mesh_results) + df = pd.DataFrame(results) + metrics = {} + for metric, series in df.items(): + metrics[f"{metric}"] = series.mean() + metrics[f"{metric}_median"] = series.median() + metrics[f"{metric}_q75"] = series.quantile(0.75) + metrics["loss"] = metrics["mse"] + + # Move model back to training mode and training device + self.model.train() + self.model = self.model.to(self.device) + + return metrics + + @property + def _eval_dataset_tags(self): + """Eval dataset tags. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + return {"eval"} + + def _make_data_loader(self, dataset, batch_size, shuffle): + """Creates a data loader. + + Parameters + ---------- + dataset : torch.nn.utils.data.Dataset + Dataset. + batch_size : int + Batch size. + shuffle : bool + Whether the dataset is shuffled. + + Returns + ------- + dataloader + Data loader. + """ + return torch_geometric.data.DataLoader( + dataset, batch_size=batch_size, shuffle=shuffle, num_workers=0, pin_memory=False + ) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/wrappers.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..60b236f35ef22766cef83d5ab954b8d22f3d7816 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/arteries/wrappers.py @@ -0,0 +1,153 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import nn +from xformers.ops.fmha import BlockDiagonalMask + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_oriented_plane, embed_point, embed_scalar, extract_translation + + +def build_attention_mask(inputs): + """Construct attention mask from pytorch geometric batch. + + Parameters + ---------- + inputs : torch_geometric.data.Batch + Data batch. + + Returns + ------- + attention_mask : xformers.ops.fmha.BlockDiagonalMask + Block-diagonal attention mask: within each sample, each token can attend to each other + token. + """ + return BlockDiagonalMask.from_seqlens(torch.bincount(inputs.batch).tolist()) + + +class ArteryBaselineWrapper(nn.Module): + """Wraps around simple baselines (like a Transformer) for the artery experiment. + + We use the following parameterization of the artery mesh: + - the node positions of the arterial mesh + - the mesh normals + - the geodesic distance to the inlet + + Parameters + ---------- + net : torch.nn.Module + Model that accepts inputs with 7 channels and returns outputs with 3 channels. + """ + + def __init__(self, net): + super().__init__() + self.net = net + + def forward(self, inputs): + """Wrapped forward pass.""" + mask = build_attention_mask(inputs) + x = torch.cat([inputs.pos, inputs.norm, inputs.geo[:, None]], 1)[None] + return self.net(x, attention_mask=mask) + + +class ArteryGATrWrapper(BaseWrapper): + """Wraps around GATr for the arterial wall-shear-stress prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + GATr model that accepts inputs with 3 multivector channels and 1 scalar channel, and + returns outputs with 1 multivector channel and 1 scalar channel. + """ + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def build_attention_mask( + self, + inputs, + mv=None, + s=None, + ): + """Construct block-diagonal attention mask.""" + return build_attention_mask(inputs) + + def embed_into_ga(self, inputs): + """Embeds raw artery data into the geometric algebra. + + We use the following parameterization of the artery mesh: + - the node positions of the arterial mesh, represented as points + - the mesh normals, represented as oriented planes + - the geodesic distance to the inlet, represented as scalars + + Parameters + ---------- + inputs : torch_geometric.data.Batch + Raw artery data. + + Returns + ------- + multivectors : torch.Tensor with shape (batchsize * num_items, num_mv_channels, 16) + Multivector embeddings of the geometric information in the dataset. + scalars : torch.Tensor with shape (batchsize * num_items, num_s_channels) + Auxiliary scalars, which in this dataset are just dummy placeholders. + """ + + # Get interesting features from PyG object + num_items = len(inputs.pos) + pos = inputs.pos.reshape(1, num_items, 1, 3) # (batch, items, channels, 3) + mesh_normals = inputs.norm.reshape(1, num_items, 1, 3) # (batch, items, channels, 3) + inlet_distance = inputs.geo.reshape(1, num_items, 1, 1) # (batch, items, channels, 1) + + # NaN debugging + assert torch.all(torch.isfinite(pos)) + assert torch.all(torch.isfinite(mesh_normals)) + assert torch.all(torch.isfinite(inlet_distance)) + + # Embed in GA + positions = embed_point(pos) + mesh_normals = embed_oriented_plane(mesh_normals, pos) + inlet_distance = embed_scalar(inlet_distance) + + # NaN debugging + assert torch.all(torch.isfinite(positions)) + assert torch.all(torch.isfinite(mesh_normals)) + assert torch.all(torch.isfinite(inlet_distance)) + + # Concatenate along channel dimension + mv = torch.concatenate( + [positions, mesh_normals, inlet_distance], dim=2 + ) # (batch, items, 3, 16) + + # Dummy scalar + s = torch.zeros(1, num_items, 1, device=mv.device, dtype=mv.dtype) + + return mv, s + + def extract_from_ga(self, multivector, scalars): + """Extracts the predicted wall shear stress from the output multivectors. + + We parameterize the wall shear stress as translation vectors. + + Parameters + ---------- + multivector : torch.Tensor with shape (1, batchsize * num_items, num_mv_channels, 16) + Multivector outputs. + scalars : torch.Tensor with shape (1, batchsize * num_items, num_s_channels) + Scalar outputs. + + Returns + ------- + wss : torch.Tensor with shape (1, batchsize * num_items, 3) + Predicted wall shear stress vectors. + regularization : None + Regularization term. As there is no regularizer in this experiment, we return None. + """ + # Check channels of inputs. Object numbers are free. + assert multivector.shape[0] == scalars.shape[0] == 1 + assert multivector.shape[2:] == (1, 16) + + # Extract wall shear stress + wss = extract_translation(multivector[:, :, 0, :]) # (1, objects, 3) + + return wss, None diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_experiment.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..80665574db9cf102c6f72a07860fbc31dca06c84 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_experiment.py @@ -0,0 +1,774 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import logging +import time +from collections import defaultdict +from contextlib import nullcontext +from pathlib import Path +from typing import Dict, Optional + +import matplotlib +import mlflow +import numpy as np +import pandas as pd +import seaborn as sns +import torch +from hydra.core.config_store import ConfigStore +from hydra.utils import instantiate +from omegaconf import OmegaConf +from torch import nn +from torch.utils.data import DataLoader +from torch_ema import ExponentialMovingAverage +from tqdm import tqdm, trange + +import gatr.primitives.attention +import gatr.utils.logger +from gatr.layers import SelfAttentionConfig +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.logger import logger +from gatr.utils.misc import NaNError, flatten_dict, frequency_check, get_batchsize, get_device +from gatr.utils.mlflow import log_mlflow +from gatr.utils.plotting import MATPLOTLIB_PARAMS + +cs = ConfigStore.instance() +cs.store(name="base_attention", node=SelfAttentionConfig) +cs.store(name="base_mlp", node=MLPConfig) + + +class BaseExperiment: + """Base experiment manager class. + + To be subclassed by experiment-specific manager classes. + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + # Store config + self.cfg = cfg + + # Device, dtype, backend + self.device, self.dtype = self._init_backend() + + # Initialize state + self.model: Optional[nn.Module] = None + self.ema = None + self.optim = None + self.scheduler = None + + self.metrics = {} + self._best_state = None + self._training_start_time: Optional[float] = None + + # Initialize folder and logger + self._initialize_experiment_folder() + self._initialize_logger() + self._silence_the_lambs() + + # Training hooks: list of (state, hook_function) + self._hooks = [] + + def __call__(self, train=True, evaluate=True): + """Performs experiment as outlined below. + + - initializes all the logistics + - instantiates model (if necessary) + - loads checkpoint (if applicable) + - trains model (if `train`) + - evaluates model (if `eval`) + + Parameters + ---------- + train : bool + Whether to train the model. + evaluate : bool + Whether to evaluate the model. + """ + + experiment_id = self._initialize_experiment() + + with mlflow.start_run(experiment_id=experiment_id, run_name=self.cfg.run_name): + self._save_config() + + # Create / load model + if self.model is None: + self.create_model() + self.load_model() + + # Train + if train: + self.train() + # Save model + self.save_model("model_final.pt") + + # Evaluate + if evaluate: + self.evaluate() + + logger.info("Anders nog iets?") + return self.metrics + + def create_model(self): + """Create self.model according to the specification in self.cfg.""" + + # Create model + self.model = self._create_model() + assert self.model is not None + self.optim, self.scheduler = self._create_optimizer_and_scheduler() + + # Report number of parameters + num_parameters = sum(p.numel() for p in self.model.parameters() if p.requires_grad) + log_mlflow("efficiency.num_parameters", float(num_parameters), step=0) + logger.info(f"Model has {num_parameters / 1e6:.2f}M learnable parameters") + + # Create exponential moving average object + if self.cfg.training.ema: + logger.info("Using EMA for validation and eval") + self.ema = ExponentialMovingAverage( + self.model.parameters(), decay=self.cfg.training.ema_decay + ) + else: + logger.debug("Not using EMA") + self.ema = None + + def load_model(self, checkpoint=None): + """Loads a model checkpoint from disk. + + Parameters + ---------- + checkpoint : None or str or pathlib.Path + Path to checkpoint. If None, self.cfg.checkpoint is used. + """ + + # If model hasn't been created yet, do that first + if self.model is None: + self.create_model() + assert self.model is not None + + if checkpoint is None: + checkpoint = self.cfg.checkpoint + + if checkpoint is not None: + logger.info(f"Loading model checkpoint from {checkpoint}") + state_dict = torch.load(checkpoint, map_location="cpu") + self.model.load_state_dict(state_dict) + + if self.cfg.training.ema: + ema_checkpoint = checkpoint.replace(".pt", "_ema.pt") + logger.info(f"Loading EMA checkpoint from {ema_checkpoint}") + state_dict = torch.load(ema_checkpoint, map_location="cpu") + assert self.ema is not None + self.ema.load_state_dict(state_dict) + + def train(self): + """High-level training function.""" + assert self.model is not None + + logger.info("Starting training") + + # Prepare data + train_data = self._load_dataset("train") + train_loader = self._make_data_loader( + train_data, batch_size=self.cfg.training.batchsize, shuffle=True + ) + val_data = self._load_dataset("val") + eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize) + val_loader = self._make_data_loader(val_data, batch_size=eval_batchsize, shuffle=False) + + # Training + num_epochs = (self.cfg.training.steps - 1) // ( + (len(train_data) - 1) // self.cfg.training.batchsize + 1 + ) + 1 + logger.info( + f"Training for {self.cfg.training.steps} steps, that is, {num_epochs} epochs on a " + f"dataset of size {len(train_data)} with batchsize {self.cfg.training.batchsize}" + ) + + # Prepare book-keeping + self._best_state = {"state_dict": None, "loss": None, "step": None} + self._training_start_time = time.time() + + # GPU + self.model = self.model.to(self.device) + if self.ema: + self.ema.to(self.device) + + # Loop over epochs + step = 0 + for epoch in trange( + num_epochs, desc="Training epochs", disable=not self.cfg.training.progressbar + ): + log_mlflow("train.epoch", epoch, step=step) + epoch_start = time.perf_counter() + self.model.train() + + # Loop over steps + for data in train_loader: + self._step(data, step, val_data, val_loader) + if step >= self.cfg.training.steps: + break + step += 1 + + logger.debug(f"Finished epoch {epoch} in {time.perf_counter() - epoch_start} seconds") + + logger.debug("Finished training") + + # Final validation loop + if ( + self.cfg.training.validate_every_n_steps is not None + and self.cfg.training.validate_every_n_steps > 0 + ): + self.validate(val_loader, step) + + # Wrap up early stopping + if ( + self.cfg.training.early_stopping + and self._best_state["step"] is not None + and self._best_state["step"] < step + ): + logger.info( + f'Early stopping after step {self._best_state["step"]} ' + f'with validation loss {self._best_state["loss"]}' + ) + self.model.load_state_dict(self._best_state["state_dict"]) + else: + logger.debug("Not using early stopping") + + def validate(self, dataloader, step): + """Runs validation loop, logs results, and may store state dict for early stopping. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Validation dataloader. + step : int + Current step number. + """ + assert self.model is not None + + # Compute validation metrics, using EMA if available + if self.ema is not None: + with self.ema.average_parameters(): + metrics = self._compute_metrics(dataloader) + else: + metrics = self._compute_metrics(dataloader) + + # Log + self.metrics["val"] = metrics + logger.info(f"Validation loop at step {step}:") + for key, value in metrics.items(): + log_mlflow(f"val.{key}", value, step=step) + logger.info(f" {key} = {value}") + + # Early stopping: compare val loss to last val loss + new_val_loss = metrics["loss"] + assert self._best_state is not None + if self._best_state["loss"] is None or new_val_loss < self._best_state["loss"]: + self._best_state["loss"] = new_val_loss + self._best_state["state_dict"] = self.model.state_dict().copy() + self._best_state["step"] = step + + def evaluate(self): + """Evaluates self.model on all eval datasets and logs the results.""" + + # Should we evaluate with EMA in addition to without? + ema_values = [False] + if self.ema is not None: + ema_values.append(True) + + # Loop over evaluation datasets + dfs = {} + for tag in self._eval_dataset_tags: + dataset = self._load_dataset(tag) + eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize) + dataloader = self._make_data_loader(dataset, batch_size=eval_batchsize, shuffle=False) + + # Loop over EMA on / off + for ema in ema_values: + # Effective tag name + full_tag = (tag + "_ema") if ema else tag + + # Run evaluation + if ema: + with self.ema.average_parameters(): + metrics = self._compute_metrics(dataloader) + else: + metrics = self._compute_metrics(dataloader) + + # Log results + self.metrics[full_tag] = metrics + logger.info(f"Ran evaluation on dataset {full_tag}:") + for key, val in metrics.items(): + logger.info(f" {key} = {val}") + log_mlflow(f"eval.{full_tag}.{key}", val) + + # Store results in csv file + # Pandas does not like scalar values, have to be iterables + test_metrics_ = {key: [val] for key, val in metrics.items()} + df = pd.DataFrame.from_dict(test_metrics_) + df.to_csv(Path(self.cfg.exp_dir) / "metrics" / f"eval_{full_tag}.csv", index=False) + dfs[full_tag] = df + return dfs + + def save_model(self, filename=None): + """Save model in experiment folder. + + Parameters + ---------- + filename : None or str + Filename to save the model to. + """ + + assert self.model is not None + if filename is None: + filename = "model.pt" + + model_path = Path(self.cfg.exp_dir) / "models" / filename + logger.info(f"Saving model at {model_path}") + torch.save(self.model.state_dict(), model_path) + + if self.ema is not None: + ema_path = Path(self.cfg.exp_dir) / "models" / filename.replace(".pt", "_ema.pt") + logger.debug(f"Saving EMA model at {ema_path}") + assert ema_path != model_path + torch.save(self.ema.state_dict(), ema_path) + + def register_hook(self, function, step=None, every_steps=None): + """Registers a hook. + + Hooks are functions called either at a specific step or every n steps during training. + """ + assert (step is None) != (every_steps is None) + self._hooks.append((step, every_steps, function)) + + def _init_backend(self): + """Initializes device, dtype, and attention implementation.""" + + # Device + device = get_device() + logger.debug(f"Training on {device}") + + # Dtype + if self.cfg.training.float16 and torch.cuda.is_bf16_supported(): + dtype = torch.bfloat16 + logger.info("Training on bfloat16") + elif self.cfg.training.float16: + dtype = torch.float16 + logger.info("Training on float16 (bfloat16 is not supported by environment)") + else: + dtype = torch.float32 + logger.info("Training on float32") + + # Attention implementation + torch.backends.cuda.enable_flash_sdp(self.cfg.training.enable_flash_sdp) + torch.backends.cuda.enable_math_sdp(self.cfg.training.enable_math_sdp) + torch.backends.cuda.enable_mem_efficient_sdp(self.cfg.training.enable_mem_efficient_sdp) + if self.cfg.training.force_xformers: + logger.debug("Forcing use of xformers' attention implementation") + gatr.primitives.attention.FORCE_XFORMERS = True + + return device, dtype + + def _initialize_experiment(self): + """Initialize experiment folder (and plenty of other initialization thingies).""" + + # Initialize MLflow experiment + experiment_id = self._initialize_mlflow() + + # Silence other loggers (thanks MLflow) + self._silence_the_lambs() + + # Re-initialize logger - this is annoying, something in the way that MLflow interacts with + # logging means that we otherwise get duplicate logging to stdout + self._initialize_logger() + + # Print config to log + logger.info(f"Running experiment at {self.cfg.exp_dir}") + logger.debug(f"Config: \n{OmegaConf.to_yaml(self.cfg)}") + + # Set random seed + torch.random.manual_seed(self.cfg.seed) + np.random.seed(self.cfg.seed) + + # Initialize plotting + self._init_plt() + + return experiment_id + + def _initialize_experiment_folder(self): + """Creates experiment folder.""" + + exp_dir = Path(self.cfg.exp_dir).resolve() + subfolders = [ + exp_dir / "models", + exp_dir / "figures", + exp_dir / "metrics", + exp_dir / "data", + ] + + # Create experiment subfolders (main folder will be automatically created as well) + for subdir in subfolders: + if subdir.exists(): + logger.warning(f"Warning: directory {subdir} already exists!") + subdir.mkdir(parents=True, exist_ok=True) + + def _initialize_logger(self): + """Initializes logging.""" + + # In sweeps (multiple experiments in one job) we don't want to set up the handlers again + if gatr.utils.logger.logging_initialized: + logger.info("Logger already initialized - hi again!") + return + + logger.setLevel(logging.DEBUG if self.cfg.debug else logging.INFO) + formatter = logging.Formatter( + "[%(asctime)-19.19s %(levelname)-1.1s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S" + ) + + file_handler = logging.FileHandler(Path(self.cfg.exp_dir) / "output.log") + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + logger.addHandler(stream_handler) + + # This is important to avoid duplicate log outputs + # See https://stackoverflow.com/questions/7173033/duplicate-log-output-when-using-python-logging-module # pylint:disable=line-too-long + logger.propagate = False + + gatr.utils.logger.logging_initialized = True + logger.info("Hoi.") + + def _initialize_mlflow(self): + """Initializes all things related to MLflow tracking.""" + + # Set up MLflow tracking location + Path(self.cfg.mlflow.db).parent.mkdir(exist_ok=True) + mlflow.set_tracking_uri(f"sqlite:///{Path(self.cfg.mlflow.db).resolve()}") + + # Set up MLflow experiment + Path(self.cfg.mlflow.artifacts).mkdir(exist_ok=True) + try: + experiment_id = mlflow.create_experiment( + self.cfg.exp_name, + artifact_location=f"file:{Path(self.cfg.mlflow.artifacts).resolve()}", + ) + logger.info(f"Created experiment {self.cfg.exp_name} with ID {experiment_id}") + except mlflow.exceptions.MlflowException: + pass # Experiment exists already + + # Set MLflow experiment details + experiment = mlflow.set_experiment(self.cfg.exp_name) + experiment_id = experiment.experiment_id + artifact_loc = experiment.artifact_location + + logger.info( + f"Set experiment {self.cfg.exp_name} with ID {experiment_id}," + f" artifact location {artifact_loc}" + ) + + return experiment_id + + @staticmethod + def _silence_the_lambs(): + """Silences other loggers.""" + for name, other_logger in logging.root.manager.loggerDict.items(): + if not "gatr_experiment" in name: + other_logger.level = logging.WARNING + + @staticmethod + def _init_plt(): + """Initializes matplotlib's rcparams to look good.""" + + sns.set_style("whitegrid") + matplotlib.rcParams.update(MATPLOTLIB_PARAMS) + + def _save_config(self): + """Stores the config in the experiment folder and tracks it with mlflow.""" + + # Save config + config_filename = Path(self.cfg.exp_dir) / "config.yml" + logger.info(f"Saving config at {config_filename}") + with open(config_filename, "w", encoding="utf-8") as file: + file.write(OmegaConf.to_yaml(self.cfg)) + + # Store config as MLflow params + for key, value in flatten_dict(self.cfg).items(): + log_mlflow(key, value, kind="param") + + def _create_model(self): + """Creates the model from the config. + + Returns + ------- + model : torch.nn.Module + A randomly initialized model, following the specification in self.cfg.model + """ + + # Hydra magic! + return instantiate(self.cfg.model) + + def _create_optimizer_and_scheduler(self): + """Creates optimizer and scheduler. + + Returns + ------- + optim : torch.optim.Optimizer + Adam optimizer for the parameters of self.model. + sched : torch.optim.lr_scheduler.LRScheduler + Exponential LR scheduler for optim. + """ + + optim = torch.optim.Adam( + self.model.parameters(), + lr=self.cfg.training.lr, + weight_decay=self.cfg.training.weight_decay, + ) + + num_scheduler_steps = self.cfg.training.steps // self.cfg.training.update_lr_every_n_steps + if num_scheduler_steps > 0: + gamma = self.cfg.training.lr_decay ** (1 / num_scheduler_steps) + else: + gamma = 1.0 + scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=gamma) + + return optim, scheduler + + def _make_data_loader(self, dataset, batch_size, shuffle): + """Creates a data loader. + + Parameters + ---------- + dataset : torch.nn.utils.data.Dataset + Dataset. + batch_size : int + Batch size. + shuffle : bool + Whether the dataset is shuffled. + + Returns + ------- + dataloader + Data loader. + """ + return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle) + + def _prep_data(self, data, device=None): + """Data preparation during training loop, e.g. to move data to correct device and dtype.""" + if isinstance(data, (tuple, list)): + data = tuple(x.to(device or self.device) for x in data) + elif isinstance(data, dict): + data = ({k: x.to(device or self.device) for k, x in data.items()},) + else: + data = (data.to(device or self.device),) + + return data + + def _step(self, data, step, val_data, val_loader): + """Everything that that may happen per step.""" + + # Move data to GPU, and other and other data prep stuff + data = self._prep_data(data) + + # Forward pass + with torch.autocast( + device_type="cuda", dtype=self.dtype, enabled=self.cfg.training.float16 + ): + ctx = torch.autograd.detect_anomaly if self.cfg.training.detect_anomaly else nullcontext + with ctx(): + loss, metrics = self._forward(*data) + + # Optimizer step + grad_norm = self._optimizer_step(loss) + + # Post-step hooks: logging, validating, checkpoint saving, etc + self._post_step(loss, metrics, grad_norm, step, val_data, val_loader) + + def _post_step(self, loss, metrics, grad_norm, step, val_data, val_loader): + # Log loss and metrics + self._log(loss, metrics, grad_norm, step) + + # Debugging output + if step == 0: + logger.info(f"Finished first forward pass with loss {loss.item()}") + + # Validation loop + if frequency_check(step, self.cfg.training.validate_every_n_steps, skip_initial=True): + logger.info(f"Starting validation at step {step}") + self.validate(val_loader, step) + + # Plotting + if frequency_check( + step, self.cfg.training.plot_every_n_steps, include_fractional=(0.01, 0.1) + ): + self.visualize(val_data, step) + + # Save model checkpoint + if frequency_check(step, self.cfg.training.save_model_every_n_steps, skip_initial=True): + self.save_model(f"model_step_{step}.pt") + + # LR scheduler + if frequency_check(step, self.cfg.training.update_lr_every_n_steps, skip_initial=True): + self.scheduler.step() + logger.debug(f"Decaying LR to {self.scheduler.get_last_lr()[0]}") + log_mlflow("train.lr", self.scheduler.get_last_lr()[0], step=step) + + # Custom hooks + for hook_step, hook_every_step, hook in self._hooks: + if hook_step == step or frequency_check(step, hook_every_step): + hook(model=self.model, step=step, experiment=self) + + def _optimizer_step(self, loss): + """Optimizer step and gradient norm clipping.""" + + assert self.optim is not None + if not torch.isfinite(loss): + raise NaNError("NaN in loss!") + + self.optim.zero_grad() + loss.backward() + + # Grad norm clipping + try: + clip_norm = self.cfg.training.clip_grad_norm + grad_norm = torch.nn.utils.clip_grad_norm_( + self.model.parameters(), clip_norm, error_if_nonfinite=True + ) + grad_norm = grad_norm.cpu().item() + except RuntimeError as e: + for n, p in self.model.named_parameters(): + if not torch.isfinite(p.grad.flatten().norm()): + print(f"Non-finite grad in {n}") + raise e + + self.optim.step() + if self.ema is not None: + self.ema.update() + + return grad_norm + + def _compute_metrics(self, dataloader): + """Given a dataloader, computes all relevant metrics. Can be adapted by subclasses. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Dataloader. + + Returns + ------- + metrics : dict with str keys and float values + Metrics computed from dataset. + """ + + # Move to eval mode and eval device + assert self.model is not None + self.model.eval() + eval_device = torch.device(self.cfg.training.eval_device) + self.model = self.model.to(eval_device) + + aggregate_metrics: Dict[str, float] = defaultdict(float) + + # Loop over dataset and compute error + for data in tqdm(dataloader, disable=False, desc="Evaluating"): + data = self._prep_data(data, device=eval_device) + + # Forward pass + loss, metrics = self._forward(*data) + + # Weight for this batch (last batches may be smaller) + batchsize = get_batchsize(data[0]) + weight = batchsize / len(dataloader.dataset) + + # Book-keeping + aggregate_metrics["loss"] += loss.item() * weight + for key, val in metrics.items(): + aggregate_metrics[key] += val * weight + + # Move model back to training mode and training device + self.model.train() + self.model = self.model.to(self.device) + + # Return metrics + return aggregate_metrics + + def _log(self, loss, metrics, grad_norm, step): + """Log to MLflow. + + Parameters + ---------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + grad_norm : float + Gradient norm + """ + + if not frequency_check(step, self.cfg.training.log_every_n_steps): + return + + metrics["loss"] = loss.item() + metrics["grad_norm"] = grad_norm + metrics["step"] = step + assert self._training_start_time is not None + metrics["time_total_s"] = time.time() - self._training_start_time + metrics["time_per_step_s"] = (time.time() - self._training_start_time) / (step + 1) + + for key, values in metrics.items(): + log_mlflow(f"train.{key}", values, step=step) + + def _load_dataset(self, tag): + """Loads dataset. To be implemented by subclasses. + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + raise NotImplementedError + + def _forward(self, *data): + """Model forward pass. To be implemented by subclasses. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + raise NotImplementedError + + def visualize(self, dataset, step): + """Visualization function. + + To be implemented by subclasses. + """ + + @property + def _eval_dataset_tags(self): + """Eval dataset tags, to be implemented by subclasses. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + return {"eval"} diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_wrapper.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..b78af1f4c16a4ed43a0508c9c9f5ad70e65138f0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/base_wrapper.py @@ -0,0 +1,142 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import nn + + +class BaseWrapper(nn.Module): + """Base GATr wrapper. + + To be subclassed by experiment-specific wrapper classes. + + Parameters + ---------- + net : torch.nn.Module + GATr network. + scalars : bool + Whether the GATr model uses auxiliary scalars in its inputs and outputs. (In hidden + representations, GATr uses auxiliary scalars always.) + return_other : bool + Whether the wrapper should return regularization terms in addition to the model predictions. + """ + + def __init__(self, net, scalars=True, return_other=True): + super().__init__() + self.net = net + self.scalars = scalars + self.return_other = return_other + + def build_attention_mask( + self, inputs, mv=None, s=None + ): # pylint: disable=unused-argument,redundant-returns-doc + """Construct attention mask. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs to wrapped network. + mv : torch.Tensor + Multivector embedding of inputs. + s : torch.Tensor + Auxiliary scalar embedding of inputs. + + Returns + ------- + attention_mask : None or torch.Tensor or xformers.ops.fmha.BlockDiagonalMask + Attention mask. + """ + return None + + def forward(self, inputs: torch.Tensor): + """Wrapped forward pass pass. + + Parses inputs into GA + scalar representation, calls the forward pass of the wrapped net, + and extracts the outputs from the GA + scalar representation again. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. Only returned if + `self.return_other`. + """ + + multivector, scalars = self.embed_into_ga(inputs) + mask = self.build_attention_mask( # pylint: disable=assignment-from-none + inputs, mv=multivector, s=scalars + ) + multivector_outputs, scalar_outputs = self.net( + multivector, scalars=scalars, attention_mask=mask + ) + outputs, other = self.extract_from_ga(multivector_outputs, scalar_outputs) + outputs = self.postprocess_results(inputs, outputs) + + if self.return_other: + return outputs, other + + return outputs + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + raise NotImplementedError + + def extract_from_ga(self, multivector, scalars): + """Extracts raw outputs from the GATr multivector + scalar outputs. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from GATr. + scalars : torch.Tensor or None + Scalar outputs from GATr. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + raise NotImplementedError + + def postprocess_results(self, inputs, outputs): # pylint: disable=unused-argument + """Postprocesses the outputs extracted from the GA representation. + + To be implemented by subclasses, optionally (by default, no postprocessing is applied). + + Parameters + ---------- + inputs + Raw inputs, pre embedding. + outputs : torch.Tensor + Raw outputs, pre postprocessing. + + Returns + ------- + processed_outputs : torch.Tensor + Raw outputs, after postprocessing. + """ + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05420100f17fb51777fef5d63baf69df607dcd14 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .dataset import NBodyDataset +from .experiment import NBodyExperiment +from .simulator import NBodySimulator +from .wrappers import ( + NBodyBaselineWrapper, + NBodyGATrWrapper, + NBodySE3TransformerWrapper, + NBodySEGNNWrapper, +) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/dataset.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..117e97b5495572a1d967d207f98753f46c4bd425 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/dataset.py @@ -0,0 +1,76 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +import torch + + +class NBodyDataset(torch.utils.data.Dataset): + """N-body prediction dataset. + + Loads data generated with generate_nbody_dataset.py from disk. + + Parameters + ---------- + filename : str or pathlib.Path + Path to the npz file with the dataset to be loaded. + subsample : None or float + If not None, defines the fraction of the dataset to be used. For instance, `subsample=0.1` + uses just 10% of the samples in the dataset. + keep_trajectories : bool + Whether to keep the full particle trajectories in the dataset. They are neither needed + for training nor evaluation, but can be useful for visualization. + """ + + def __init__(self, filename, subsample=None, keep_trajectories=False): + super().__init__() + self.x, self.y, self.trajectories = self._load_data( + filename, subsample, keep_trajectories=keep_trajectories + ) + + def __len__(self): + """Returns the number of samples in the dataset.""" + return len(self.x) + + def __getitem__(self, idx): + """Returns the `idx`-th sample from the dataset.""" + return self.x[idx], self.y[idx] + + @staticmethod + def _load_data(filename, subsample=None, keep_trajectories=False): + """Loads data from file and converts to input and output tensors.""" + # Load data from file + npz = np.load(filename, "r") + m, x_initial, v_initial, x_final = ( + npz["m"], + npz["x_initial"], + npz["v_initial"], + npz["x_final"], + ) + + # Convert to tensors + m = torch.from_numpy(m).to(torch.float32).unsqueeze(2) + x_initial = torch.from_numpy(x_initial).to(torch.float32) + v_initial = torch.from_numpy(v_initial).to(torch.float32) + x_final = torch.from_numpy(x_final).to(torch.float32) + + # Concatenate into inputs and outputs + x = torch.cat((m, x_initial, v_initial), dim=2) # (batchsize, num_objects, 7) + y = x_final # (batchsize, num_objects, 3) + + # Optionally, keep raw trajectories around (for plotting) + if keep_trajectories: + trajectories = npz["trajectories"] + else: + trajectories = None + + # Subsample + if subsample is not None and subsample < 1.0: + n_original = len(x) + n_keep = int(round(subsample * n_original)) + assert 0 < n_keep <= n_original + x = x[:n_keep] + y = y[:n_keep] + if trajectories is not None: + trajectories = trajectories[:n_keep] + + return x, y, trajectories diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/experiment.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c746f9fa80cf26d2da99399703e48ab3bf8a0f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/experiment.py @@ -0,0 +1,99 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from pathlib import Path + +import torch + +from gatr.experiments.base_experiment import BaseExperiment +from gatr.experiments.nbody.dataset import NBodyDataset + + +class NBodyExperiment(BaseExperiment): + """Experiment manager for n-body prediction. + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + super().__init__(cfg) + self._mse_criterion = torch.nn.MSELoss() + self._mae_criterion = torch.nn.L1Loss(reduction="mean") + + def _load_dataset(self, tag): + """Loads dataset. + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + + if tag == "train": + subsample_fraction = self.cfg.data.subsample + else: + subsample_fraction = None + + filename = Path(self.cfg.data.data_dir) / f"{tag}.npz" + keep_trajectories = tag == "val" + return NBodyDataset( + filename, subsample=subsample_fraction, keep_trajectories=keep_trajectories + ) + + def _forward(self, *data): + """Model forward pass. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + + # Forward pass + assert self.model is not None + x, y = data + y_pred, reg = self.model(x) + + # Compute loss + mse = self._mse_criterion(y_pred, y) + output_reg = torch.mean(reg) + loss = mse + self.cfg.training.output_regularization * output_reg + + # Additional metrics + mae = self._mae_criterion(y_pred, y) + metrics = dict( + mse=mse.item(), rmse=loss.item() ** 0.5, output_reg=output_reg.item(), mae=mae.item() + ) + + return loss, metrics + + @property + def _eval_dataset_tags(self): + """Eval dataset tags. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + + # Only evaluate on object_generalization dataset when method supports variable token number + assert self.model is not None + if self.model.supports_variable_items: + return {"eval", "e3_generalization", "object_generalization"} + + return {"eval", "e3_generalization"} diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/simulator.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ffedae9f88bfb94cd20473c37aa791bd8bb649 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/simulator.py @@ -0,0 +1,223 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +from scipy.stats import special_ortho_group + +from gatr.utils.misc import sample_log_uniform, sample_uniform_in_circle + + +class NBodySimulator: + """Simulator for the n-body dataset. + + Each sample consists of the positions of a n particicles (1 star and n - 1 planets), both before + and after the evolution of 100 time steps. The particle masses are also part of the sample. + + The data is generated in the following way: + 1. The masses for the star and planets are sampled. + 2. The initial planet positions are sampled around the origin in the x-y plane. The star is at + (0, 0). + 3. The initial planet velocities are given by the velocity of a stable circular orbit, plus some + noise. + The star is initially at rest. + 4. The initial state is translated and rotated to an arbitrary position and orientation in + space. + 5. The final state is computed (using Newton's equations of gravity and Newton's method). + 6. To avoid annoying outliers, samples where the initial and final position of any object + are more than outlier_threshold are removed. + + We use units where G = 1. + + Parameters + ---------- + time : float + Overall time period between initial and final state. + time_steps : int + Number of time steps that the time window is divided into for Euler integration. + star_mass_range : tuple of float + Minimum and maximum mass for the star. + planet_mass_range : tuple of float + Minimum and maximum mass for the planets. + radius_range : tuple of float + Minimum and maximum initial distance of the planets from the star. + vel_std : float + Noise scale for the initial planet velocity. + shift_std : float + Noise scale for the spatial translation. + ood_shift : float + Noise scale for the spatial translation for the translated sample. + outlier_threshold : float + Threshold for the rejection of outlier samples in which initial and final positions differ + substantially. + """ + + def __init__( + self, + time=0.1, + time_steps=100, + star_mass_range=(1.0, 10.0), + planet_mass_range=(0.01, 0.1), + radius_range=(0.1, 1.0), + vel_std=0.01, + shift_std=20.0, + ood_shift=200.0, + outlier_threshold=2.0, + ): + self.time = time + self.delta_t = time / time_steps + self.time_steps = time_steps + self.star_mass_range = star_mass_range + self.planet_mass_range = planet_mass_range + self.radius_range = radius_range + self.vel_std = vel_std + self.shift_std = shift_std + self.ood_shift = ood_shift + self.outlier_threshold = outlier_threshold + + def sample(self, num_samples, num_planets=5, domain_shift=False): + """Samples from gravity problem. + + Parameters + ---------- + num_samples : int + Number of samples. + num_planets : int + Number of planets in the dataset (as there is always a single star, we have + `n = num_planets + 1`). + domain_shift : bool + Whether to sample with larger spatial translation to generate domain-shifted data. + """ + + # Sample a bit more initially, to make up for outlier removal later + num_candidates = int(round(1.1 * num_samples)) + + # 1. Sample planet masses + star_mass = sample_log_uniform(*self.star_mass_range, size=(num_candidates, 1)) + planet_masses = sample_log_uniform( + *self.planet_mass_range, size=(num_candidates, num_planets) + ) + masses = np.concatenate((star_mass, planet_masses), axis=1) + + # 2. Sample initial positions in x-y plane around origin + planet_pos = np.zeros((num_candidates, num_planets, 3)) + planet_pos[..., :2] = sample_uniform_in_circle( + num_candidates * num_planets, + min_radius=self.radius_range[0], + max_radius=self.radius_range[1], + ).reshape((num_candidates, num_planets, 2)) + x_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_pos), axis=1) + + # 3. Sample initial velocities, approximately as stable circular orbits + planet_vel = self._sample_planet_velocities(star_mass, planet_pos) + v_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_vel), axis=1) + + # 4. Translate, rotate, permute + masses, x_initial, v_initial = self._shift_and_rotate( + masses, x_initial, v_initial, domain_shift=domain_shift + ) + + # 5. Evolve Newtonian gravity + x_final, trajectory = self._simulate(masses, x_initial, v_initial) + + # 6. Remove outliers + max_distance = np.max(np.linalg.norm(x_final - x_initial, axis=-1), axis=-1) + mask = max_distance <= self.outlier_threshold + masses, x_initial, v_initial, x_final, trajectory = ( + masses[mask], + x_initial[mask], + v_initial[mask], + x_final[mask], + trajectory[mask], + ) + + # Cut down to requested number + masses, x_initial, v_initial, x_final, trajectory = ( + masses[:num_samples], + x_initial[:num_samples], + v_initial[:num_samples], + x_final[:num_samples], + trajectory[:num_samples], + ) + + return masses, x_initial, v_initial, x_final, trajectory + + def _sample_planet_velocities(self, star_mass, x): + """Samples planet velocities around those that give stable circular orbits.""" + + batchsize, num_planets, _ = x.shape + + # Defines rotation plane. Clockwise or counterclockwise is random for each planet. + orientation = np.zeros((batchsize, num_planets, 3)) + orientation[:, :, 2] = np.random.choice( + a=[-1.0, 1.0], size=(batchsize, num_planets), p=[0.5, 0.5] + ) + + # Compute stable velocities + star_mass = star_mass[:, :, np.newaxis] # (batchsize, 1, 1) + radii = np.linalg.norm(x, axis=-1)[:, :, np.newaxis] # (batchsize, num_planets, 1) + v_stable = np.cross(orientation, x) * star_mass**0.5 / radii**1.5 + + # Add noise + v = v_stable + np.random.normal(scale=self.vel_std, size=(batchsize, num_planets, 3)) + + return v + + def _shift_and_rotate(self, m, x, v, domain_shift=False): + """Performs random E(3) transformations and permutations on given positions / velocities.""" + + batchsize, num_objects, _ = x.shape + + # Permutations over objects + for i in range(batchsize): + perm = np.random.permutation(num_objects) + m[i] = m[i][perm] + x[i] = x[i][perm, :] + v[i] = v[i][perm, :] + + # Rotations from Haar measure + rotations = special_ortho_group(3).rvs(size=batchsize).reshape(batchsize, 1, 3, 3) + x = np.einsum("bnij,bnj->bni", rotations, x) + v = np.einsum("bnij,bnj->bni", rotations, v) + + # Translations + shifts = np.random.normal(scale=self.shift_std, size=(batchsize, 1, 3)) + x = x + shifts + + # OOD shift + if domain_shift: + shifts = np.array([self.ood_shift, 0, 0]).reshape((1, 1, 3)) + x = x + shifts + + return m, x, v + + def _simulate(self, m, x_initial, v_initial): + """Evolves an initial state under Newtonian equations of motions.""" + + x, v = x_initial, v_initial + trajectory = [x_initial] + + for _ in range(self.time_steps): + a = self._compute_accelerations(m, x) + v = v + self.delta_t * a + x = x + self.delta_t * v + trajectory.append(x) + + return x, np.array(trajectory).transpose([1, 2, 0, 3]) + + @staticmethod + def _compute_accelerations(m, x): + """Computes accelerations for a set of point masses according to Newtonian gravity.""" + batchsize, num_objects, _ = x.shape + mm = m.reshape((batchsize, 1, num_objects, 1)) * m.reshape( + (batchsize, num_objects, 1, 1) + ) # (b, n, n, 1) + + distance_vectors = x.reshape((batchsize, 1, num_objects, 3)) - x.reshape( + (batchsize, num_objects, 1, 3) + ) # (b, n, n, 3) + distances = np.linalg.norm(distance_vectors, axis=-1)[:, :, :, np.newaxis] # (b, n, n, 1) + distances[np.abs(distances) < 1e-9] = 1.0 + + forces = distance_vectors * mm / distances**3 # (b, n, n, 3) + accelerations = np.sum(forces, axis=2) / m.reshape(batchsize, num_objects, 1) # (b, n, 3) + + return accelerations # (b, n, 3) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/wrappers.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0693a8baa3763815fff4bda4eb54ece1f5a578 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/experiments/nbody/wrappers.py @@ -0,0 +1,489 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import dgl +import numpy as np +import torch +from e3nn.o3 import Irreps, spherical_harmonics +from torch import nn +from torch_geometric.data import Data +from torch_geometric.nn import knn_graph +from torch_scatter import scatter + +from gatr.baselines.gcan import GCAGNN +from gatr.baselines.transformer import BaselineAxialTransformer, BaselineTransformer +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import ( + embed_point, + embed_scalar, + embed_translation, + extract_point, + extract_point_embedding_reg, +) +from gatr.utils.misc import make_full_edge_index + + +def embed_nbody_data_in_pga(inputs): + """Represent the n-body initial state in PGA multivectors. + + Masses are represented as scalars, positions as trivectors, and velocities as bivectors + (like translations). All three are summed (this is equivalent to concatenation, as an equi + linear layer can easily separate the grades again). + + This function is used both by the GATr and by the GCAN wrappers. + + Parameters + ---------- + inputs : torch.Tensor with shape (batchsize, objects, 7) + n-body initial state: a concatenation of masses, initial positions, and initial + velocities along the feature dimension. + + Returns + ------- + multivector : torch.Tensor with shape (batchsize, objects, 1, 16) + GA embedding. + """ + + # Build one multivector holding masses, points, and velocities for each object + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + masses = embed_scalar(masses) # (batchsize, objects, 16) + points = inputs[:, :, 1:4] # (batchsize, objects, 3) + points = embed_point(points) # (batchsize, objects, 16) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + velocities = embed_translation(velocities) # (batchsize, objects, 16) + multivector = masses + points + velocities # (batchsize, objects, 16) + + # Insert channel dimension + multivector = multivector.unsqueeze(2) # (batchsize, objects, 1, 16) + + return multivector + + +class NBodyGATrWrapper(BaseWrapper): + """Wraps around GATr for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + GATr model that accepts inputs with 1 multivector channel and 1 scalar channel, and + returns outputs with 1 multivector channel and 1 scalar channel. + """ + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=True) + self.supports_variable_items = True + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + Parameters + ---------- + inputs : torch.Tensor with shape (batchsize, objects, 7) + n-body initial state: a concatenation of masses, initial positions, and initial + velocities along the feature dimension. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector representation of masses, positions, and velocities. + scalar_inputs : torch.Tensor or None + Dummy auxiliary scalars, containing no information. + """ + batchsize, num_objects, _ = inputs.shape + + # Build one multivector holding masses, positions, and velocities for each object + multivector = embed_nbody_data_in_pga(inputs) + + # Scalar inputs are not really needed here + scalars = torch.zeros((batchsize, num_objects, 1), device=inputs.device) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Extracts raw outputs from the GATr multivector + scalar outputs. + + We parameterize the predicted final positions as points. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from GATr. + scalars : torch.Tensor or None + Scalar outputs from GATr. + + Returns + ------- + outputs : torch.Tensor + Predicted final-state positions. + other : torch.Tensor + Regularization terms. + """ + + # Check channels of inputs. Batchsize and object numbers are free. + assert multivector.shape[2:] == (1, 16) + assert scalars.shape[2:] == (1,) + + # Extract position + points = extract_point(multivector[:, :, 0, :]) + + # Extract non-point components and compute regularization + other = extract_point_embedding_reg(multivector[:, :, 0, :]) + reg = torch.sum(other**2, dim=[1, 2]) + if self.scalars: + reg = reg + torch.sum(scalars**2, dim=[1, 2]) + + return points, reg + + +class NBodyBaselineWrapper(nn.Module): + """Wraps around simple baselines (MLP or Transformer) for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + Model that accepts inputs with 7 channels and returns outputs with 3 channels. + """ + + def __init__(self, net): + super().__init__() + self.net = net + self.supports_variable_items = isinstance( + net, (BaselineTransformer, BaselineAxialTransformer) + ) + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + """ + batchsize = inputs.shape[0] + return self.net(inputs), torch.zeros(batchsize, device=inputs.device) + + +class NBodySEGNNWrapper(nn.Module): + """Wraps around the SEGNN baseline for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + SEGNN model that accepts inputs with inputs with 2 vector channels and 1 scalar channel, + and returns outputs with 1 vector channel. + """ + + def __init__(self, net, neighbors, lmax_attr, canonicalize_mode="com"): + super().__init__() + + self.net = net + + self.canonicalize_mode = canonicalize_mode + self.neighbors = neighbors + self.transform_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + self.supports_variable_items = True + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + + Raises + ------ + ValueError + If `self.canonicalize_mode` is invalid. + """ + batchsize, num_objects, _ = inputs.shape + + # Separate into scalars and vectors + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + locations = inputs[:, :, 1:4] # (batchsize, objects, 3) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + + # Canonicalize + if self.canonicalize_mode == "com": + weights = masses + elif self.canonicalize_mode == "heaviest": + weights = torch.exp(2.0 * masses.double()) + elif self.canonicalize_mode == "even": + weights = torch.ones_like(masses) + else: + raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}") + + com = torch.sum( + weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(), + dim=-2, + keepdim=True, + ).float() + locations = locations - com + + # Represent as graph + graph = Data(pos=locations.view(-1, 3), vel=velocities.view(-1, 3), mass=masses.view(-1, 1)) + batch = torch.arange(0, batchsize, device=inputs.device) + graph.batch = batch.repeat_interleave(num_objects).to(inputs.device, torch.long) + graph.edge_index = knn_graph(locations.view(-1, 3), self.neighbors, graph.batch) + + graph = self._augment_gravity_graph(graph) # Add O3 attributes + + # Push through model + pred_shift = self.net(graph) + pred_shift = pred_shift.view(batchsize, num_objects, 3) + predictions = ( + locations + pred_shift + ) # The model predicts the shift, not the final positions + + # Undo canonicalization + predictions = predictions + com + + return predictions, torch.zeros(batchsize, device=inputs.device) + + def _augment_gravity_graph(self, graph): + """SEGNN feature engineering for n-body experiments. + + Constructs node features (position relative to mean position, velocity embedding, absolute + velocity) and edge features (pairwise distances, product of charges / masses). + """ + + pos = graph.pos + vel = graph.vel + mass = graph.mass + + prod_mass = mass[graph.edge_index[0]] * mass[graph.edge_index[1]] + rel_pos = pos[graph.edge_index[0]] - pos[graph.edge_index[1]] + edge_dist = torch.sqrt(rel_pos.pow(2).sum(1, keepdims=True)) + + graph.edge_attr = spherical_harmonics( + self.transform_attr_irreps, rel_pos, normalize=True, normalization="integral" + ) + vel_embedding = spherical_harmonics( + self.transform_attr_irreps, vel, normalize=True, normalization="integral" + ) + graph.node_attr = ( + scatter(graph.edge_attr, graph.edge_index[1], dim=0, reduce="mean") + vel_embedding + ) + + vel_abs = torch.sqrt(vel.pow(2).sum(1, keepdims=True)) + + graph.x = torch.cat((pos, vel, vel_abs), 1) # Note that pos is here already canonicalized + graph.additional_message_features = torch.cat((edge_dist, prod_mass), dim=-1) + return graph + + +class NBodySE3TransformerWrapper(nn.Module): + """Wraps around the SE3-Transformer baseline for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + SE3-Transformer model. + """ + + def __init__(self, net, canonicalize_to_com=True, canonicalize_mode="com"): + super().__init__() + + self.net = net + self.canonicalize_to_com = canonicalize_to_com + self.canonicalize_mode = canonicalize_mode + self.supports_variable_items = True + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + + Raises + ------ + ValueError + If `self.canonicalize_mode` is invalid. + """ + batchsize, num_objects, _ = inputs.shape + + # Separate into scalars and vectors + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + locations = inputs[:, :, 1:4] # (batchsize, objects, 3) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + + # Canonicalize to center-of-mass frame if requested + if self.canonicalize_to_com: + if self.canonicalize_mode == "com": + weights = masses + elif self.canonicalize_mode == "heaviest": + weights = torch.exp(2.0 * masses.double()) + else: + raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}") + com = torch.sum( + weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(), + dim=-2, + keepdim=True, + ).float() + locations = locations - com + else: + com = torch.zeros_like(locations) + + # Represent as graph + graphs = self._build_graphs(locations, velocities, masses) + + # Push through model + predictions = self.net(graphs) + predictions = predictions[:, 0, :] # Only positions, not velocities + predictions = predictions.view(batchsize, num_objects, 3) + predictions = ( + locations + predictions + ) # Model predicts positions relative to initial pos, make it absolute + + # Undo canonicalization + if self.canonicalize_to_com: + predictions = predictions + com + + return predictions, torch.zeros(batchsize, device=inputs.device) + + def _build_graphs(self, locations, velocities, masses): + """Builds graph for a full batch.""" + graphs = [ + self._build_graph(loc, vel, m) for loc, vel, m in zip(locations, velocities, masses) + ] + graphs = dgl.batch(graphs) + + return graphs + + def _build_graph(self, locations, velocities, masses): + """Builds graph for a single sample.""" + n_points = len(locations) + indices_src, indices_dst = self._fully_connected_idx(n_points) + graph = dgl.DGLGraph((indices_src, indices_dst)).to(locations.device) + graph.ndata["x"] = torch.unsqueeze(locations, dim=1) # [N, 1, 3] + graph.ndata["v"] = torch.unsqueeze(velocities, dim=1) # [N, 1, 3] + graph.ndata["c"] = torch.unsqueeze(masses, dim=1) # [N, 1, 1] + graph.edata["d"] = locations[indices_dst] - locations[indices_src] # relative postions + graph.edata["w"] = masses[indices_dst] * masses[indices_src] + return graph + + @staticmethod + def _fully_connected_idx(num_atoms): + """Creates source and destination indices for a fully connected graph.""" + src = [] + dst = [] + for i in range(num_atoms): + for j in range(num_atoms): + if i != j: + src.append(i) + dst.append(j) + return np.array(src), np.array(dst) + + +class NBodyGCANWrapper(nn.Module): + """Wraps around GCA-MLP and GCA-GNN baselines for the n-body experiment. + + Parameters + ---------- + net : torch.nn.Module + GCAN model that accepts inputs with multivector inputs with 1 channel and + returns multivector outputs with 1 channel. + """ + + def __init__(self, net, geometric_batching=False): + super().__init__() + self.net = net + self._geometric_batching = geometric_batching + self.supports_variable_items = isinstance(net, GCAGNN) + + def forward(self, inputs: torch.Tensor): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + """ + + multivector = embed_nbody_data_in_pga(inputs) + + if self._geometric_batching: + # PyG-style batching, with a single batch-token dimension and edge list + edge_index = self.make_edge_index(inputs) + multivector = multivector.view(-1, *multivector.shape[2:]) + multivector_outputs = self.net(multivector, edge_index=edge_index) + multivector_outputs = multivector_outputs.view( + inputs.shape[0], -1, *multivector_outputs.shape[1:] + ) + else: + # Standard batching, with (batch, token, ...) tensors + multivector_outputs = self.net(multivector) + + outputs, reg = self.extract_from_ga(multivector_outputs) + return outputs, reg + + @staticmethod + def extract_from_ga(multivector): + """Extracts predicted positions from PGA multivectors.""" + # Check channels of inputs. Batchsize and object numbers are free. + assert multivector.shape[2:] == (1, 16) + + # Extract position + points = extract_point(multivector[:, :, 0, :]) + + # Extract non-point components and compute regularization + other = extract_point_embedding_reg(multivector[:, :, 0, :]) + reg = torch.sum(other**2, dim=[1, 2]) + return points, reg + + @staticmethod + def make_edge_index(inputs): + """Constructs an edge index for fully connected graph.""" + batchsize, num_items, _ = inputs.shape + return make_full_edge_index( + num_items, batchsize=batchsize, self_loops=False, device=inputs.device + ) + + def to(self, *args, **kwargs): + """Send to device. + + Overwritten to also move the CliffordAlgebra object, which is not an nn.Module. + """ + resursively_move_gcan_pga(self, *args, **kwargs) + super().to(*args, **kwargs) + return self + + +def resursively_move_gcan_pga(net, *args, **kwargs): + """Moves all PGA instances in GCAN component to device / dtype.""" + try: + net.pga.to(*args, **kwargs) + except AttributeError: + pass + + for child in net.children(): + resursively_move_gcan_pga(child, *args, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d358aaf1fc027eea4f16fdbb39d8de030afd5d75 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .object import ( + embed_3d_object, + embed_3d_object_two_vec, + extract_3d_object, + extract_3d_object_two_vec, +) +from .plane import embed_oriented_plane, extract_oriented_plane +from .point import embed_point, extract_point, extract_point_embedding_reg +from .pseudoscalar import embed_pseudoscalar, extract_pseudoscalar +from .reflection import embed_reflection, extract_reflection +from .rotation import embed_rotation, extract_rotation +from .scalar import embed_scalar, extract_scalar +from .translation import embed_translation, extract_translation diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/object.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/object.py new file mode 100644 index 0000000000000000000000000000000000000000..faa706ee5f18e93815c3ec1281fe891dd137074c --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/object.py @@ -0,0 +1,212 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Optional + +import torch + +from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane +from gatr.interface.point import embed_point, extract_point +from gatr.interface.rotation import embed_rotation, extract_rotation +from gatr.interface.translation import embed_translation +from gatr.primitives.bilinear import geometric_product, outer_product +from gatr.primitives.linear import reverse + + +def embed_3d_object( + position: torch.Tensor, orientation: torch.Tensor, explicit_point: bool = False +) -> torch.Tensor: + """Embeds the pose of a 3D object PGA multivectors. + + The pose is given by a position and a orientation quaternion. The latter is assumed to follow + the pybullet conventions: to be given in Hamilton convention, where ijk = -1, and with the + scalar component last (ijkw order). + + The embedding contains three plane multivectors v_i with + ``` + v_i = T(p) R(q) e_i reverse(T(p) R(q)) + ``` + where `T()` is the translation embedding, `R()` is the rotation embedding, and `e_i` are the PGA + basis vectors. + + If `explicit_point`, then a fourth multivector represents the position itself. + + References + ---------- + Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478 + + Parameters + ---------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1) + explicit_point : bool + If True, in addition to the three planes we provide the explicit point representation + `P(p)`. + + Returns + ------- + multivector : torch.Tensor with shape (..., n_channels, 16) + Embedding into multivectors, with `n_channels = 4 if explicit_point else 3`. + """ + + # Check inputs + assert position.shape[-2:] == (1, 3) + assert orientation.shape[-2:] == (1, 4) + + # Basis planes + basis = torch.zeros(3, 16, dtype=position.dtype, device=position.device) # (3, 16) + basis[:, 2:5] = torch.eye( + 3, dtype=position.dtype, device=position.device + ) # basis[i] has e_i = 1 + + # Translation and rotation + t = embed_translation(position) # (..., 1, 16) + r = embed_rotation(orientation) # (..., 1, 16) + tr = geometric_product(t, r) # (..., 1, 16) + + # Construct embedding + embedding = geometric_product(geometric_product(tr, basis), reverse(tr)) # (..., 3, 16) + + # Optional point embedding + if explicit_point: + point = embed_point(position) + embedding = torch.cat((embedding, point), dim=-2) # (..., 4, 16) + + return embedding + + +def extract_3d_object( + multivector: torch.Tensor, + normalize_quaternion: bool = True, + sign_reference: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """Extracts 3D position and quaternion orientation from the multivector embedding of an object. + + This function inverts embed_3d_object(). + + The extraction starts from three (plane) MVs v_i and is based on the magic equation + ``` + P(p) = v_1 ^ v_2 ^ v_3 + q = (1 + sum_i _E e_i) + ``` + where `_E` is the projection of v_i to the Euclidean vector components. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 3 or 4, 16) + Object embedding. + normalize_quaternion : bool + Whether to normalize quaternions. + sign_reference : None or torch.Tensor + If provided, used to fix the (ambiguous) sign of the orientation quaternion. + + Returns + ------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1). + """ + + # Split inputs + v = [multivector[..., [i], :] for i in range(3)] # (..., 1, 16) each + + # Basis vectors + basis = torch.zeros(3, 16, dtype=multivector.dtype, device=multivector.device) # (3, 16) + basis[:, 2:5] = torch.eye( + 3, dtype=multivector.dtype, device=multivector.device + ) # basis[i] has e_i = 1 + projection = torch.sum(basis, dim=0) # (16) + + # Extract position + if multivector.shape[-2] == 4: + position = extract_point(multivector[..., [3], :]) # (..., 1, 3) + else: + position = outer_product(outer_product(v[0], v[1]), v[2]) # (..., 1, 16) + position = extract_point(position) # (..., 1, 3) + + # Extract orientation + orientation = torch.zeros(16, dtype=multivector.dtype, device=multivector.device) + orientation[0] = 1.0 + for vi, ei in zip(v, basis): + vi_proj = projection * vi # Project to Euclidean vector components + orientation = orientation + geometric_product(vi_proj, ei) # Magic equation + + quat = extract_rotation(orientation, normalize=normalize_quaternion) + + # Fix quaternion sign + if sign_reference is not None: + sign = torch.sign(torch.sum(sign_reference * quat, dim=-1, keepdim=True)) + quat = sign * quat + + return position, quat + + +def embed_3d_object_two_vec(position: torch.Tensor, orientation: torch.Tensor) -> torch.Tensor: + """Embeds the pose of a 3D object in two-vec parameterization into the PGA. + + The inputs consist of the position of an object and two vectors that specify its orientation. + These two vectors can be generated from a rotation matrix by taking the first two column + vectors. + + The embedding contains three planes and a point, just like embed_3d_object(). + + Parameters + ---------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 6) + Orientation in two-vec parameterization + + Returns + ------- + multivector : torch.Tensor with shape (..., 4, 16) + Embedding into three multivectors. + """ + + # Check inputs + assert position.shape[-2:] == (1, 3) + assert orientation.shape[-2:] == (1, 6) + + # Point + point_embedding = embed_point(position) # (..., 1, 16) + + # Two-vec -> three vectors + orientation = orientation.reshape(*orientation.shape[:-2], 2, 3) + third_vec = torch.linalg.cross(orientation[..., [0], :], orientation[..., [1], :]) + orientation = torch.cat((orientation, third_vec), dim=-2) + + # Embed orientation as planes + orientation_embedding = embed_oriented_plane(orientation, position) # (..., 3, 16) + + embedding = torch.cat((point_embedding, orientation_embedding), dim=-2) # (..., 4, 16) + return embedding + + +def extract_3d_object_two_vec(multivector: torch.Tensor) -> torch.Tensor: + """Extracts 3D position and two-vec orientation from the multivector embedding of an object. + + This inverts embed_3d_object_two_vec(). + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 3, 16) + Object embedding. + + Returns + ------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 6) + Two-vec param of orientation + """ + + # Position + position = extract_point(multivector[..., [0], :]) # (..., 1, 3) + + # Orientation + orientation = extract_oriented_plane(multivector[..., [1, 2], :]) # (..., 2, 3) + orientation = orientation.reshape(*multivector.shape[:-2], 1, 6) # (..., 1, 6) + + return position, orientation diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/plane.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..4036bebcf09c5a5ddbe21b70164d4391935235b2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/plane.py @@ -0,0 +1,72 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import Tensor + +from gatr.interface.translation import embed_translation +from gatr.primitives.bilinear import geometric_product + + +def embed_oriented_plane(normal: Tensor, position: Tensor) -> Tensor: + """Embeds an (oriented plane) in the PGA. + + Following L. Dorst, the plane is represent as PGA vectors. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + position : torch.Tensor with shape (..., 3) + One position on the plane. + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = normal.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=normal.dtype, device=normal.device) + + # Embedding a plane through origin into vectors + multivector[..., 2:5] = normal[..., :] + + # Shift away from origin by translating + translation = embed_translation(position) + inverse_translation = embed_translation(-position) + multivector = geometric_product( + geometric_product(translation, multivector), inverse_translation + ) + + return multivector + + +def extract_oriented_plane(multivector: torch.Tensor) -> torch.Tensor: + """Extracts the normal on an oriented plane from a multivector. + + Currently, this function does *not* extract a support point for the plane (or the distance to + the origin). + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + + Returns + ------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + """ + + return multivector[..., 2:5] diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/point.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/point.py new file mode 100644 index 0000000000000000000000000000000000000000..b350cfd100be736189d1949af1ae2bdfb83e27be --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/point.py @@ -0,0 +1,104 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Functions that embed points in the geometric algebra.""" + + +import torch + + +def embed_point(coordinates: torch.Tensor) -> torch.Tensor: + """Embeds 3D points in multivectors. + + We follow the convention used in the reference below and map points to tri-vectors. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + coordinates : torch.Tensor with shape (..., 3) + 3D coordinates + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = coordinates.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=coordinates.dtype, device=coordinates.device) + + # Embedding into trivectors + # Homogeneous coordinates: unphysical component / embedding dim, x_123 + multivector[..., 14] = 1.0 + multivector[..., 13] = -coordinates[..., 0] # x-coordinate embedded in x_023 + multivector[..., 12] = coordinates[..., 1] # y-coordinate embedded in x_013 + multivector[..., 11] = -coordinates[..., 2] # z-coordinate embedded in x_012 + + return multivector + + +def extract_point( + multivector: torch.Tensor, divide_by_embedding_dim: bool = True, threshold: float = 1e-3 +) -> torch.Tensor: + """Given a multivector, extract any potential 3D point from the trivector components. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + divide_by_embedding_dim : bool + Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it + may not be good for NN training. + threshold : float + Minimum value of the additional, unphysical component. Necessary to avoid exploding values + or NaNs when this unphysical component of the homogeneous coordinates becomes small. + + Returns + ------- + coordinates : torch.Tensor with shape (..., 3) + 3D coordinates corresponding to the trivector components of the multivector. + """ + + coordinates = torch.cat( + [-multivector[..., [13]], multivector[..., [12]], -multivector[..., [11]]], dim=-1 + ) + + # Divide by embedding dim + if divide_by_embedding_dim: + embedding_dim = multivector[ + ..., [14] + ] # Embedding dimension / scale of homogeneous coordinates + embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold) + coordinates = coordinates / embedding_dim + + return coordinates + + +def extract_point_embedding_reg(multivector: torch.Tensor) -> torch.Tensor: + """Given a multivector x, returns |x_{123}| - 1. + + Put differently, this is the deviation of the norm of a pseudoscalar component from 1. + This can be used as a regularization term when predicting point positions, to avoid x_123 to + be too close to 0. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + + Returns + ------- + regularization : torch.Tensor with shape (..., 1) + |multivector_123| - 1. + """ + + return torch.abs(multivector[..., [14]]) - 1.0 diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/pseudoscalar.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/pseudoscalar.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16ed0bfcdccb6f75f99040b12d956f982a7f17 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/pseudoscalar.py @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_pseudoscalar(pseudoscalars: torch.Tensor) -> torch.Tensor: + """Embeds a pseudoscalar tensor into multivectors. + + Parameters + ---------- + pseudoscalars: torch.Tensor with shape (..., 1) + Pseudoscalar inputs. + + Returns + ------- + multivectors: torch.Tensor with shape (..., 16) + Multivector outputs. `multivectors[..., [15]]` is the same as `pseudoscalars`. + The other components are zero. + """ + + non_scalar_shape = list(pseudoscalars.shape[:-1]) + [15] + non_scalar_components = torch.zeros( + non_scalar_shape, device=pseudoscalars.device, dtype=pseudoscalars.dtype + ) + embedding = torch.cat((non_scalar_components, pseudoscalars), dim=-1) + + return embedding + + +def extract_pseudoscalar(multivectors: torch.Tensor) -> torch.Tensor: + """Extracts pseudoscalar components from multivectors. + + Parameters + ---------- + multivectors: torch.Tensor with shape (..., 16) + Multivector inputs. + + Returns + ------- + pseudoscalars: torch.Tensor with shape (..., 1) + Pseudoscalar component of multivectors. + """ + + return multivectors[..., [15]] diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/reflection.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..926a478a4346c3f04bad52adbcddca3e042d87d2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/reflection.py @@ -0,0 +1,56 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Functions that create multivectors representing elements of the Pin group.""" + + +from torch import Tensor + +from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane + + +def embed_reflection(normal: Tensor, position: Tensor) -> Tensor: + """Embeds the reflection on a plane in multivectors. + + Following L. Dorst, this is represented as a PGA vector. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + normal : Tensor with shape (..., 3) + Normal to the reflection plane. + position : Tensor with shape (..., 3) + One position on the reflection plane. + + Returns + ------- + multivector : Tensor with shape (..., 16) + Embedding into multivector. + """ + + return embed_oriented_plane(normal, position) + + +def extract_reflection(multivector: Tensor) -> Tensor: + """Extracts the normal on an reflection plane from a multivector. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + + Returns + ------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + """ + + return extract_oriented_plane(multivector) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/rotation.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..0dba94b83d8be06fddd15a5ccc354601974b4370 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/rotation.py @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_rotation(quaternion: torch.Tensor) -> torch.Tensor: + """Embeds 3D rotations in multivectors. + + We follow the convention used in Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra + PGA", and map rotations around the origin to bivectors. + + For quaternions we use the "Hamilton" convention, where ijk = -1 (*not* the JPL convention + where ijk = 1). For details, see "Why and How to Avoid the Flipped Quaternion Multiplication" + by Sommer et al. (2018) + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478 + + Parameters + ---------- + quaternion : torch.Tensor with shape (..., 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1) + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = quaternion.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=quaternion.dtype, device=quaternion.device) + + # Embedding into bivectors + # w component of quaternion is the scalar component of the multivector + multivector[..., 0] = quaternion[..., 3] + multivector[..., 8] = -quaternion[..., 2] # k component of quaternion is the bivector -e12 + multivector[..., 9] = quaternion[..., 1] # j component of quaternion is the bivector e13 + multivector[..., 10] = -quaternion[..., 0] # i component of quaternion is the bivector -e23 + + return multivector + + +def extract_rotation(multivector: torch.Tensor, normalize: bool = False) -> torch.Tensor: + """Extracts the represented rotation quaternion from the multivector's bivector components. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + normalize : bool + Whether to normalize the quaternion to unit norm. + + Returns + ------- + quaternion : torch.Tensor with shape (..., 4) + quaternion in ijkw order and Hamilton convention (ijk = -1) + """ + + quaternion = torch.cat( + [ + -multivector[..., [10]], + multivector[..., [9]], + -multivector[..., [8]], + multivector[..., [0]], + ], + dim=-1, + ) + + if normalize: + quaternion = quaternion / torch.linalg.norm(quaternion, dim=-1, keepdim=True) + + return quaternion diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/scalar.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1bfcaefcb0fe30b29675d97baea5f6abcf2554 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/scalar.py @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_scalar(scalars: torch.Tensor) -> torch.Tensor: + """Embeds a scalar tensor into multivectors. + + Parameters + ---------- + scalars: torch.Tensor with shape (..., 1) + Scalar inputs. + + Returns + ------- + multivectors: torch.Tensor with shape (..., 16) + Multivector outputs. `multivectors[..., [0]]` is the same as `scalars`. The other components + are zero. + """ + + non_scalar_shape = list(scalars.shape[:-1]) + [15] + non_scalar_components = torch.zeros( + non_scalar_shape, device=scalars.device, dtype=scalars.dtype + ) + embedding = torch.cat((scalars, non_scalar_components), dim=-1) + + return embedding + + +def extract_scalar(multivectors: torch.Tensor) -> torch.Tensor: + """Extracts scalar components from multivectors. + + Parameters + ---------- + multivectors: torch.Tensor with shape (..., 16) + Multivector inputs. + + Returns + ------- + scalars: torch.Tensor with shape (..., 1) + Scalar component of multivectors. + """ + + return multivectors[..., [0]] diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/translation.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/translation.py new file mode 100644 index 0000000000000000000000000000000000000000..97f50b30c55119ea2890228587b54595177318b8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/interface/translation.py @@ -0,0 +1,83 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_translation(translation_vector: torch.Tensor) -> torch.Tensor: + """Embeds a 3D translation in multivectors. + + In our convention, a translation vector is embedded into a combination of the scalar and + bivector components. + + We have (in agreement with Eq. (82) of the reference below) that + ``` + T(t) = 1 - e_0 / 2 (t_1 e_1 + t_2 e_2 + t_3 e_3) . + ``` + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + translation_vector : torch.Tensor with shape (..., 3) + Vectorial amount of translation. + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = translation_vector.shape[:-1] + multivector = torch.zeros( + *batch_shape, 16, dtype=translation_vector.dtype, device=translation_vector.device + ) + + # Embedding into trivectors + multivector[..., 0] = 1.0 # scalar + multivector[..., 5:8] = ( + -0.5 * translation_vector[..., :] + ) # Translation vector embedded in x_0i with i = 1, 2, 3 + + return multivector + + +def extract_translation( + multivector: torch.Tensor, divide_by_embedding_dim=False, threshold: float = 1e-3 +) -> torch.Tensor: + """Given a multivector, extract a 3D translation vector from the bivector components. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + divide_by_embedding_dim : bool + Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it + may not be good for NN training. + threshold : float + Minimum value of the additional, unphysical component. Necessary to avoid exploding values + or NaNs when this unphysical component of the homogeneous coordinates becomes small. + + Returns + ------- + translation : torch.Tensor with shape (..., 3) + 3D components of the translation vector. + """ + + translation_vector = -2.0 * multivector[..., 5:8] + + # Divide by embedding dim + if divide_by_embedding_dim: + embedding_dim = multivector[..., [0]] + embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold) + translation_vector = translation_vector / embedding_dim + + return translation_vector diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55575f4d3ed3bb9810576604585aea2d77329bc4 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .attention.config import SelfAttentionConfig +from .attention.positional_encoding import ApplyRotaryPositionalEncoding +from .attention.self_attention import SelfAttention +from .dropout import GradeDropout +from .layer_norm import EquiLayerNorm +from .linear import EquiLinear +from .mlp.geometric_bilinears import GeometricBilinear +from .mlp.mlp import GeoMLP +from .mlp.nonlinearities import ScalarGatedNonlinearity diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cb55ce7227c907bb4d5383128de0c4ca26adb8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .config import SelfAttentionConfig +from .self_attention import SelfAttention diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/attention.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..489fe2c99bef8b49bfc9c3a24cfa2c84b39d9513 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/attention.py @@ -0,0 +1,92 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Self-attention layers.""" + +from functools import partial + +import torch +from torch import nn + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.primitives.attention import geometric_attention, lin_square_normalizer + + +class GeometricAttention(nn.Module): + """Geometric attention layer. + + This is the main attention mechanism used in GATr. Thanks to the nonlinear features, the + scaled-dot-product attention takes into account the Euclidean distance. + + Given multivector and scalar queries, keys, and values, this layer computes: + + ``` + attn_weights[..., i, j] = softmax_j[ + weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + config : SelfAttentionConfig + Attention configuration. + """ + + def __init__(self, config: SelfAttentionConfig) -> None: + super().__init__() + + self.normalizer = partial(lin_square_normalizer, epsilon=config.normalizer_eps) + self.log_weights = nn.Parameter( + torch.zeros((config.num_heads, 1, config.hidden_mv_channels)) + ) + + def forward(self, q_mv, k_mv, v_mv, q_s, k_s, v_s, attention_mask=None): + """Forward pass through geometric attention. + + Given multivector and scalar queries, keys, and values, this forward pass computes: + + ``` + attn_weights[..., i, j] = softmax_j[ + weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + attention_mask: None or Tensor or AttentionBias + Optional attention mask. + """ + + weights = self.log_weights.exp() + h_mv, h_s = geometric_attention( + q_mv, + k_mv, + v_mv, + q_s, + k_s, + v_s, + normalizer=self.normalizer, + weights=weights, + attn_mask=attention_mask, + ) + + return h_mv, h_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/config.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/config.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e8dd878e3a85ba0f31802d1a6ffd509f5722ba --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/config.py @@ -0,0 +1,106 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Optional + + +@dataclass +class SelfAttentionConfig: + """Configuration for attention. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + num_heads : int + Number of attention heads. + in_s_channels : int + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int + Output scalar channels. If None, no scalars are expected nor returned. + additional_qk_mv_channels : int + Whether additional multivector features for the keys and queries will be provided. + additional_qk_s_channels : int + Whether additional scalar features for the keys and queries will be provided. + normalizer : str + Normalizer function to use in sdp_dist attention + normalizer_eps : float + Small umerical constant for stability in the normalizer in sdp_dist attention + multi_query: bool + Whether to do multi-query attention + attention_type : {"scalar", "geometric", "sdp_dist"} + Whether the attention mechanism is based on the scalar product or also the join. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_enc_base : int + Base for the frequencies in the positional encoding. + output_init : str + Initialization scheme for final linear layer + increase_hidden_channels : int + Factor by which to increase the number of hidden channels (both multivectors and scalars) + dropout_prob : float or None + Dropout probability + """ + + multi_query: bool = True + in_mv_channels: Optional[int] = None + out_mv_channels: Optional[int] = None + in_s_channels: Optional[int] = None + out_s_channels: Optional[int] = None + num_heads: int = 8 + additional_qk_mv_channels: int = 0 + additional_qk_s_channels: int = 0 + normalizer_eps: Optional[float] = 1e-3 + pos_encoding: bool = False + pos_enc_base: int = 4096 + output_init: str = "default" + checkpoint: bool = True + increase_hidden_channels: int = 2 + dropout_prob: Optional[float] = None + + def __post_init__(self): + """Type checking / conversion.""" + if isinstance(self.dropout_prob, str) and self.dropout_prob.lower() in ["null", "none"]: + self.dropout_prob = None + + @property + def hidden_mv_channels(self) -> Optional[int]: + """Returns the number of hidden multivector channels.""" + + if self.in_mv_channels is None: + return None + + return max(self.increase_hidden_channels * self.in_mv_channels // self.num_heads, 1) + + @property + def hidden_s_channels(self) -> Optional[int]: + """Returns the number of hidden scalar channels.""" + + if self.in_s_channels is None: + return None + + hidden_s_channels = max( + self.increase_hidden_channels * self.in_s_channels // self.num_heads, 4 + ) + + # When using positional encoding, the number of scalar hidden channels needs to be even. + # It also should not be too small. + if self.pos_encoding: + hidden_s_channels = (hidden_s_channels + 1) // 2 * 2 + hidden_s_channels = max(hidden_s_channels, 8) + + return hidden_s_channels + + @classmethod + def cast(cls, config: Any) -> SelfAttentionConfig: + """Casts an object as SelfAttentionConfig.""" + if isinstance(config, SelfAttentionConfig): + return config + if isinstance(config, Mapping): + return cls(**config) + raise ValueError(f"Can not cast {config} to {cls}") diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/positional_encoding.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/positional_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..c42e107333f247ea1566136e001fced655411d23 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/positional_encoding.py @@ -0,0 +1,131 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/EleutherAI/gpt-neox/blob/737c9134bfaff7b58217d61f6619f1dcca6c484f/megatron/model/positional_embeddings.py +by EleutherAI at https://github.com/EleutherAI/gpt-neox + +Copyright (c) 2021, EleutherAI + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import torch + +from gatr.utils.einsum import cached_einsum + + +class ApplyRotaryPositionalEncoding(torch.nn.Module): + """Applies rotary position encodings (RoPE) to scalar tensors. + + References + ---------- + Jianlin Su et al, "RoFormer: Enhanced Transformer with Rotary Position Embedding", + arXiv:2104.09864 + + Parameters + ---------- + num_channels : int + Number of channels (key and query size). + item_dim : int + Embedding dimension. Should be even. + base : int + Determines the frequencies. + """ + + def __init__(self, num_channels, item_dim, base=4096): + super().__init__() + + assert ( + num_channels % 2 == 0 + ), "Number of channels needs to be even for rotary position embeddings" + + inv_freq = 1.0 / (base ** (torch.arange(0, num_channels, 2).float() / num_channels)) + self.register_buffer("inv_freq", inv_freq) + self.seq_len_cached = None + self.device_cached = None + self.cos_cached = None + self.sin_cached = None + self.item_dim = item_dim + self.num_channels = num_channels + + def forward(self, scalars: torch.Tensor) -> torch.Tensor: + """Computes rotary embeddings along `self.item_dim` and applies them to inputs. + + The inputs are usually scalar queries and keys. + + Assumes that the last dimension is the feature dimension (and is thus not suited + for multivector data!). + + Parameters + ---------- + scalars : torch.Tensor of shape (..., num_channels) + Input data. The last dimension is assumed to be the channel / feature dimension + (NOT the 16 dimensions of a multivector). + + Returns + ------- + outputs : torch.Tensor of shape (..., num_channels) + Output data. Rotary positional embeddings applied to the input tensor. + """ + + # Check inputs + assert scalars.shape[-1] == self.num_channels + + # Compute embeddings, if not already cached + self._compute_embeddings(scalars) + + # Apply embeddings + outputs = scalars * self.cos_cached + self._rotate_half(scalars) * self.sin_cached + + return outputs + + def _compute_embeddings(self, inputs): + """Computes position embeddings and stores them. + + The position embedding is computed along dimension `item_dim` of tensor `inputs` + and is stored in `self.sin_cached` and `self.cos_cached`. + + Parameters + ---------- + inputs : torch.Tensor + Input data. + """ + seq_len = inputs.shape[self.item_dim] + if seq_len != self.seq_len_cached or inputs.device != self.device_cached: + self.seq_len_cached = seq_len + self.device_cached = inputs.device + t = torch.arange(inputs.shape[self.item_dim], device=inputs.device).type_as( + self.inv_freq + ) + freqs = cached_einsum("i,j->ij", t, self.inv_freq) + emb = torch.cat((freqs, freqs), dim=-1).to(inputs.device) + + self.cos_cached = emb.cos() + self.sin_cached = emb.sin() + + # Insert appropriate amount of dimensions such that the embedding correctly enumerates + # along the item dim + item_dim = ( + self.item_dim if self.item_dim >= 0 else inputs.ndim + self.item_dim + ) # Deal with item_dim < 0 + for _ in range(item_dim + 1, inputs.ndim - 1): + self.cos_cached = self.cos_cached.unsqueeze(1) + self.sin_cached = self.sin_cached.unsqueeze(1) + + @staticmethod + def _rotate_half(inputs): + """Utility function that "rotates" a tensor, as required for rotary embeddings.""" + x1, x2 = inputs[..., : inputs.shape[-1] // 2], inputs[..., inputs.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/qkv.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/qkv.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce1503438a15a0ab83f1f74e51e6ad0b7cf91d3 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/qkv.py @@ -0,0 +1,209 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from einops import rearrange +from torch import nn + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.linear import EquiLinear + + +class QKVModule(nn.Module): + """Compute (multivector and scalar) queries, keys, and values via multi-head attention. + + Parameters + ---------- + config: SelfAttentionConfig + Attention configuration + """ + + def __init__(self, config: SelfAttentionConfig): + super().__init__() + self.in_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=3 * config.hidden_mv_channels * config.num_heads, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=None + if config.in_s_channels is None + else 3 * config.hidden_s_channels * config.num_heads, + ) + self.config = config + + def forward( + self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None + ): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Multivector inputs + scalars : torch.Tensor + Scalar inputs + additional_qk_features_mv : None or torch.Tensor + Additional multivector features that should be provided for the Q/K computation (e.g. + positions of objects) + additional_qk_features_s : None or torch.Tensor + Additional scalar features that should be provided for the Q/K computation (e.g. + object types) + + Returns + ------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + """ + + # Additional inputs + if additional_qk_features_mv is not None: + inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2) + if additional_qk_features_s is not None: + scalars = torch.cat((scalars, additional_qk_features_s), dim=-1) + + qkv_mv, qkv_s = self.in_linear( + inputs, scalars + ) # (..., num_items, 3 * hidden_channels * num_heads, 16) + qkv_mv = rearrange( + qkv_mv, + "... items (qkv hidden num_heads) x -> qkv ... num_heads items hidden x", + num_heads=self.config.num_heads, + hidden=self.config.hidden_mv_channels, + qkv=3, + ) + q_mv, k_mv, v_mv = qkv_mv # each: (..., num_heads, num_items, num_channels, 16) + + # Same, for optional scalar components + if qkv_s is not None: + qkv_s = rearrange( + qkv_s, + "... items (qkv hidden num_heads) -> qkv ... num_heads items hidden", + num_heads=self.config.num_heads, + hidden=self.config.hidden_s_channels, + qkv=3, + ) + q_s, k_s, v_s = qkv_s # each: (..., num_heads, num_items, num_channels) + else: + q_s, k_s, v_s = None, None, None + + return q_mv, k_mv, v_mv, q_s, k_s, v_s + + +class MultiQueryQKVModule(nn.Module): + """Compute (multivector and scalar) queries, keys, and values via multi-query attention. + + Parameters + ---------- + config: SelfAttentionConfig + Attention configuration + """ + + def __init__(self, config: SelfAttentionConfig): + super().__init__() + + # Q projection + self.q_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=config.hidden_mv_channels * config.num_heads, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=config.hidden_s_channels * config.num_heads, + ) + + # Key and value projections (shared between heads) + self.k_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=config.hidden_mv_channels, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=config.hidden_s_channels, + ) + self.v_linear = EquiLinear( + in_mv_channels=config.in_mv_channels, + out_mv_channels=config.hidden_mv_channels, + in_s_channels=config.in_s_channels, + out_s_channels=config.hidden_s_channels, + ) + self.config = config + + def forward( + self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None + ): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Multivector inputs + scalars : torch.Tensor + Scalar inputs + additional_qk_features_mv : None or torch.Tensor + Additional multivector features that should be provided for the Q/K computation (e.g. + positions of objects) + additional_qk_features_s : None or torch.Tensor + Additional scalar features that should be provided for the Q/K computation (e.g. + object types) + + Returns + ------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + """ + + # Additional inputs + if additional_qk_features_mv is not None: + qk_inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2) + else: + qk_inputs = inputs + if scalars is not None and additional_qk_features_s is not None: + qk_scalars = torch.cat((scalars, additional_qk_features_s), dim=-1) + else: + qk_scalars = scalars + + # Project to queries, keys, and values (multivector reps) + q_mv, q_s = self.q_linear( + qk_inputs, qk_scalars + ) # (..., num_items, hidden_channels * num_heads, 16) + k_mv, k_s = self.k_linear(qk_inputs, qk_scalars) # (..., num_items, hidden_channels, 16) + v_mv, v_s = self.v_linear(inputs, scalars) # (..., num_items, hidden_channels, 16) + + # Rearrange to (..., heads, items, channels, 16) shape + q_mv = rearrange( + q_mv, + "... items (hidden_channels num_heads) x -> ... num_heads items hidden_channels x", + num_heads=self.config.num_heads, + hidden_channels=self.config.hidden_mv_channels, + ) + k_mv = rearrange(k_mv, "... items hidden_channels x -> ... 1 items hidden_channels x") + v_mv = rearrange(v_mv, "... items hidden_channels x -> ... 1 items hidden_channels x") + + # Same for scalars + if q_s is not None: + q_s = rearrange( + q_s, + "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels", + num_heads=self.config.num_heads, + hidden_channels=self.config.hidden_s_channels, + ) + k_s = rearrange(k_s, "... items hidden_channels -> ... 1 items hidden_channels") + v_s = rearrange(v_s, "... items hidden_channels -> ... 1 items hidden_channels") + else: + q_s, k_s, v_s = None, None, None + + return q_mv, k_mv, v_mv, q_s, k_s, v_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/self_attention.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/self_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d46d52ef5b70a96f667d6ead204179d2496fa --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/attention/self_attention.py @@ -0,0 +1,143 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Self-attention layers.""" + +from typing import Optional, Tuple + +import torch +from einops import rearrange +from torch import nn + +from gatr.layers.attention.attention import GeometricAttention +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.attention.positional_encoding import ApplyRotaryPositionalEncoding +from gatr.layers.attention.qkv import MultiQueryQKVModule, QKVModule +from gatr.layers.dropout import GradeDropout +from gatr.layers.linear import EquiLinear + + +class SelfAttention(nn.Module): + """Geometric self-attention layer. + + Constructs queries, keys, and values, computes attention, and projects linearly to outputs. + + Parameters + ---------- + config : SelfAttentionConfig + Attention configuration. + """ + + def __init__(self, config: SelfAttentionConfig) -> None: + super().__init__() + + # Store settings + self.config = config + + # QKV computation + self.qkv_module = MultiQueryQKVModule(config) if config.multi_query else QKVModule(config) + + # Output projection + self.out_linear = EquiLinear( + in_mv_channels=config.hidden_mv_channels * config.num_heads, + out_mv_channels=config.out_mv_channels, + in_s_channels=None + if config.in_s_channels is None + else config.hidden_s_channels * config.num_heads, + out_s_channels=config.out_s_channels, + initialization=config.output_init, + ) + + # Optional positional encoding + self.pos_encoding: nn.Module + if config.pos_encoding: + self.pos_encoding = ApplyRotaryPositionalEncoding( + config.hidden_s_channels, item_dim=-2, base=config.pos_enc_base + ) + else: + self.pos_encoding = nn.Identity() + + # Attention + self.attention = GeometricAttention(config) + + # Dropout + self.dropout: Optional[nn.Module] + if config.dropout_prob is not None: + self.dropout = GradeDropout(config.dropout_prob) + else: + self.dropout = None + + def forward( + self, + multivectors: torch.Tensor, + additional_qk_features_mv: Optional[torch.Tensor] = None, + scalars: Optional[torch.Tensor] = None, + additional_qk_features_s: Optional[torch.Tensor] = None, + attention_mask=None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes forward pass on inputs with shape `(..., items, channels, 16)`. + + The result is the following: + + ``` + # For each head + queries = linear_channels(inputs) + keys = linear_channels(inputs) + values = linear_channels(inputs) + hidden = attention_items(queries, keys, values, biases=biases) + head_output = linear_channels(hidden) + + # Combine results + output = concatenate_heads head_output + ``` + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., num_items, channels_in, 16) + Input multivectors. + additional_qk_features_mv : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, multivector part. + scalars : None or torch.Tensor with shape (..., num_items, num_items, in_scalars) + Optional input scalars + additional_qk_features_s : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, scalar part. + scalars : None or torch.Tensor with shape (..., num_items, num_items, in_scalars) + Optional input scalars + attention_mask: None or torch.Tensor with shape (..., num_items, num_items) + Optional attention mask + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., num_items, channels_out, 16) + Output multivectors. + output_scalars : torch.Tensor with shape (..., num_items, channels_out, out_scalars) + Output scalars, if scalars are provided. Otherwise None. + """ + # Compute Q, K, V + q_mv, k_mv, v_mv, q_s, k_s, v_s = self.qkv_module( + multivectors, scalars, additional_qk_features_mv, additional_qk_features_s + ) + + # Rotary positional encoding + q_s = self.pos_encoding(q_s) + k_s = self.pos_encoding(k_s) + + # Attention layer + h_mv, h_s = self.attention(q_mv, k_mv, v_mv, q_s, k_s, v_s, attention_mask=attention_mask) + + h_mv = rearrange( + h_mv, "... n_heads n_items hidden_channels x -> ... n_items (n_heads hidden_channels) x" + ) + h_s = rearrange( + h_s, "... n_heads n_items hidden_channels -> ... n_items (n_heads hidden_channels)" + ) + + # Transform linearly one more time + outputs_mv, outputs_s = self.out_linear(h_mv, scalars=h_s) + + # Dropout + if self.dropout is not None: + outputs_mv, outputs_s = self.dropout(outputs_mv, outputs_s) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/dropout.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce686bbd20ed18a9c2a61bdc2732f5f2de21171 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/dropout.py @@ -0,0 +1,49 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant dropout layer.""" + +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives import grade_dropout + + +class GradeDropout(nn.Module): + """Grade dropout for multivectors (and regular dropout for auxiliary scalars). + + Parameters + ---------- + p : float + Dropout probability. + """ + + def __init__(self, p: float = 0.0): + super().__init__() + self._dropout_prob = p + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. Applies dropout. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., 16) + Multivector inputs. + scalars : torch.Tensor + Scalar inputs. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., 16) + Multivector inputs with dropout applied. + output_scalars : torch.Tensor + Scalar inputs with dropout applied. + """ + + out_mv = grade_dropout(multivectors, p=self._dropout_prob, training=self.training) + out_s = torch.nn.functional.dropout(scalars, p=self._dropout_prob, training=self.training) + + return out_mv, out_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/gatr_block.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/gatr_block.py new file mode 100644 index 0000000000000000000000000000000000000000..ee96806de22e9a27a3e6d3a36276e8c8fb274049 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/gatr_block.py @@ -0,0 +1,141 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from dataclasses import replace +from typing import Optional, Tuple + +import torch +from torch import nn + +from gatr.layers import SelfAttention, SelfAttentionConfig +from gatr.layers.layer_norm import EquiLayerNorm +from gatr.layers.mlp.config import MLPConfig +from gatr.layers.mlp.mlp import GeoMLP + + +class GATrBlock(nn.Module): + """Equivariant transformer block for GATr. + + This is the biggest building block of GATr. + + Inputs are first processed by a block consisting of LayerNorm, multi-head geometric + self-attention, and a residual connection. Then the data is processed by a block consisting of + another LayerNorm, an item-wise two-layer geometric MLP with GeLU activations, and another + residual connection. + + Parameters + ---------- + mv_channels : int + Number of input and output multivector channels + s_channels: int + Number of input and output scalar channels + attention: SelfAttentionConfig + Attention configuration + mlp: MLPConfig + MLP configuration + dropout_prob : float or None + Dropout probability + """ + + def __init__( + self, + mv_channels: int, + s_channels: int, + attention: SelfAttentionConfig, + mlp: MLPConfig, + dropout_prob: Optional[float] = None, + ) -> None: + super().__init__() + + # Normalization layer (stateless, so we can use the same layer for both normalization + # instances) + self.norm = EquiLayerNorm() + + # Self-attention layer + attention = replace( + attention, + in_mv_channels=mv_channels, + out_mv_channels=mv_channels, + in_s_channels=s_channels, + out_s_channels=s_channels, + output_init="small", + dropout_prob=dropout_prob, + ) + self.attention = SelfAttention(attention) + + # MLP block + mlp = replace( + mlp, + mv_channels=(mv_channels, 2 * mv_channels, mv_channels), + s_channels=(s_channels, 2 * s_channels, s_channels), + dropout_prob=dropout_prob, + ) + self.mlp = GeoMLP(mlp) + + def forward( + self, + multivectors: torch.Tensor, + scalars: torch.Tensor, + reference_mv=None, + additional_qk_features_mv=None, + additional_qk_features_s=None, + attention_mask=None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass of the transformer block. + + Inputs are first processed by a block consisting of LayerNorm, multi-head geometric + self-attention, and a residual connection. Then the data is processed by a block consisting + of another LayerNorm, an item-wise two-layer geometric MLP with GeLU activations, and + another residual connection. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., items, channels, 16) + Input multivectors. + scalars : torch.Tensor with shape (..., s_channels) + Input scalars. + reference_mv : torch.Tensor with shape (..., 16) or None + Reference multivector for the equivariant join operation in the MLP. + additional_qk_features_mv : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, multivector part. + additional_qk_features_s : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, scalar part. + attention_mask: None or torch.Tensor or AttentionBias + Optional attention mask. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., items, channels, 16). + Output multivectors + output_scalars : torch.Tensor with shape (..., s_channels) + Output scalars + """ + + # Attention block: layer norm + h_mv, h_s = self.norm(multivectors, scalars=scalars) + + # Attention block: self attention + h_mv, h_s = self.attention( + h_mv, + scalars=h_s, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + + # Attention block: skip connection + outputs_mv = multivectors + h_mv + outputs_s = scalars + h_s + + # MLP block: layer norm + h_mv, h_s = self.norm(outputs_mv, scalars=outputs_s) + + # MLP block: MLP + h_mv, h_s = self.mlp(h_mv, scalars=h_s, reference_mv=reference_mv) + + # MLP block: skip connection + outputs_mv = outputs_mv + h_mv + outputs_s = outputs_s + h_s + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/layer_norm.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f9301a78f541ce03b576c96220f0c49c5c5a55 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/layer_norm.py @@ -0,0 +1,70 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant normalization layers.""" + +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives import equi_layer_norm + + +class EquiLayerNorm(nn.Module): + """Equivariant LayerNorm for multivectors. + + Rescales input such that `mean_channels |inputs|^2 = 1`, where the norm is the GA norm and the + mean goes over the channel dimensions. + + In addition, the layer performs a regular LayerNorm operation on auxiliary scalar inputs. + + Parameters + ---------- + mv_channel_dim : int + Channel dimension index for multivector inputs. Defaults to the second-last entry (last are + the multivector components). + scalar_channel_dim : int + Channel dimension index for scalar inputs. Defaults to the last entry. + epsilon : float + Small numerical factor to avoid instabilities. We use a reasonably large number to balance + issues that arise from some multivector components not contributing to the norm. + """ + + def __init__(self, mv_channel_dim=-2, scalar_channel_dim=-1, epsilon: float = 0.01): + super().__init__() + self.mv_channel_dim = mv_channel_dim + self.epsilon = epsilon + + if scalar_channel_dim != -1: + raise NotImplementedError( + "Currently, only scalar_channel_dim = -1 is implemented, but found" + f" {scalar_channel_dim}" + ) + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. Computes equivariant LayerNorm for multivectors. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., 16) + Multivector inputs + scalars : torch.Tensor with shape (..., self.in_channels, self.in_scalars) + Scalar inputs + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., 16) + Normalized multivectors + output_scalars : torch.Tensor with shape (..., self.out_channels, self.in_scalars) + Normalized scalars. + """ + + outputs_mv = equi_layer_norm( + multivectors, channel_dim=self.mv_channel_dim, epsilon=self.epsilon + ) + normalized_shape = scalars.shape[-1:] + outputs_s = torch.nn.functional.layer_norm(scalars, normalized_shape=normalized_shape) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/linear.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f9b57180b740ef4f0121ac805564324261b603 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/linear.py @@ -0,0 +1,355 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Pin-equivariant linear layers between multivector tensors (torch.nn.Modules).""" + +from typing import Optional, Tuple, Union + +import numpy as np +import torch +from torch import nn + +from gatr.interface import embed_scalar +from gatr.primitives.linear import NUM_PIN_LINEAR_BASIS_ELEMENTS, equi_linear + + +class EquiLinear(nn.Module): + """Pin-equivariant linear layer. + + The forward pass maps multivector inputs with shape (..., in_channels, 16) to multivector + outputs with shape (..., out_channels, 16) as + + ``` + outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x] + ``` + + plus an optional bias term for outputs[..., :, 0] (biases in other multivector components would + break equivariance). + + Here basis_map are precomputed (see gatr.primitives.linear) and weights are the + learnable weights of this layer. + + If there are auxiliary input scalars, they transform under a linear layer, and mix with the + scalar components the multivector data. Note that in this layer (and only here) the auxiliary + scalars are optional. + + This layer supports four initialization schemes: + - "default": preserves (or actually slightly reducing) the variance of the data in + the forward pass + - "small": variance of outputs is approximately one order of magnitude smaller + than for "default" + - "unit_scalar": outputs will be close to (1, 0, 0, ..., 0) + - "almost_unit_scalar": similar to "unit_scalar", but with more stochasticity + + Parameters + ---------- + in_mv_channels : int + Input multivector channels + out_mv_channels : int + Output multivector channels + bias : bool + Whether a bias term is added to the scalar component of the multivector outputs + in_s_channels : int or None + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + initialization : {"default", "small", "unit_scalar", "almost_unit_scalar"} + Initialization scheme. For "default", initialize with the same philosophy as most + networks do: preserve variance (approximately) in the forward pass. For "small", + initalize the network such that the variance of the output data is approximately one + order of magnitude smaller than that of the input data. For "unit_scalar", initialize + the layer such that the output multivectors will be closer to (1, 0, 0, ..., 0). + "almost_unit_scalar" is similar, but with more randomness. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + bias: bool = True, + initialization: str = "default", + ) -> None: + super().__init__() + + # Check inputs + if initialization == "unit_scalar": + assert bias, "unit_scalar initialization requires bias" + if in_s_channels is None: + raise NotImplementedError( + "unit_scalar initialization is currently only implemented for scalar inputs" + ) + + self._in_mv_channels = in_mv_channels + + # MV -> MV + self.weight = nn.Parameter( + torch.empty((out_mv_channels, in_mv_channels, NUM_PIN_LINEAR_BASIS_ELEMENTS)) + ) + + # We only need a separate bias here if that isn't already covered by the linear map from + # scalar inputs + self.bias = ( + nn.Parameter(torch.zeros((out_mv_channels, 1))) + if bias and in_s_channels is None + else None + ) + + # Scalars -> MV scalars + self.s2mvs: Optional[nn.Linear] + if in_s_channels: + self.s2mvs = nn.Linear(in_s_channels, out_mv_channels, bias=bias) + else: + self.s2mvs = None + + # MV scalars -> scalars + if out_s_channels: + self.mvs2s = nn.Linear(in_mv_channels, out_s_channels, bias=bias) + else: + self.mvs2s = None + + # Scalars -> scalars + if in_s_channels is not None and out_s_channels is not None: + self.s2s = nn.Linear( + in_s_channels, out_s_channels, bias=False + ) # Bias would be duplicate + else: + self.s2s = None + + # Initialization + self.reset_parameters(initialization) + + def forward( + self, multivectors: torch.Tensor, scalars: Optional[torch.Tensor] = None + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Maps input multivectors and scalars using the most general equivariant linear map. + + The result is again multivectors and scalars. + + For multivectors we have: + ``` + outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x] + = sum_i linear(inputs[..., i, :], weights[j, i, :]) + ``` + + Here basis_map are precomputed (see gatr.primitives.linear) and weights are the + learnable weights of this layer. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + outputs_mv = equi_linear(multivectors, self.weight) # (..., out_channels, 16) + + if self.bias is not None: + bias = embed_scalar(self.bias) + outputs_mv = outputs_mv + bias + + if self.s2mvs is not None and scalars is not None: + outputs_mv[..., 0] += self.s2mvs(scalars) + + if self.mvs2s is not None: + outputs_s = self.mvs2s(multivectors[..., 0]) + if self.s2s is not None and scalars is not None: + outputs_s = outputs_s + self.s2s(scalars) + else: + outputs_s = None + + return outputs_mv, outputs_s + + def reset_parameters( + self, + initialization: str, + gain: float = 1.0, + additional_factor=1.0 / np.sqrt(3.0), + use_mv_heuristics=True, + ) -> None: + """Initializes the weights of the layer. + + Parameters + ---------- + initialization : {"default", "small", "unit_scalar", "almost_unit_scalar"} + Initialization scheme. For "default", initialize with the same philosophy as most + networks do: preserve variance (approximately) in the forward pass. For "small", + initalize the network such that the variance of the output data is approximately one + order of magnitude smaller than that of the input data. For "unit_scalar", initialize + the layer such that the output multivectors will be closer to (1, 0, 0, ..., 0). + "almost_unit_scalar" is similar, but with more randomness. + gain : float + Gain factor for the activations. Should be 1.0 if previous layer has no activation, + sqrt(2) if it has a ReLU activation, and so on. Can be computed with + `torch.nn.init.calculate_gain()`. + additional_factor : float + Empirically, it has been found that slightly *decreasing* the data variance at each + layer gives a better performance. In particular, the PyTorch default initialization uses + an additional factor of 1/sqrt(3) (cancelling the factor of sqrt(3) that naturally + arises when computing the bounds of a uniform initialization). A discussion of this was + (to the best of our knowledge) never published, but see + https://github.com/pytorch/pytorch/issues/57109 and + https://soumith.ch/files/20141213_gplus_nninit_discussion.htm. + use_mv_heuristics : bool + Multivector components are differently affected by the equivariance constraint. If + `use_mv_heuristics` is set to True, we initialize the weights for each output + multivector component differently, with factors determined empirically to preserve the + variance of each multivector component in the forward pass. + """ + + # Prefactors depending on initialization scheme + mv_component_factors, mv_factor, mvs_bias_shift, s_factor = self._compute_init_factors( + initialization, gain, additional_factor, use_mv_heuristics + ) + + # Following He et al, 1502.01852, we aim to preserve the variance in the forward pass. + # A sufficient criterion for this is that the variance of the weights is given by + # `Var[w] = gain^2 / fan`. + # Here `gain^2` is 2 if the previous layer has a ReLU nonlinearity, 1 for the initial layer, + # and some other value in other situations (we may not care about this too much). + # More importantly, `fan` is the number of connections: the number of input elements that + # get summed over to compute each output element. + + # Let us fist consider the multivector outputs. + self._init_multivectors(mv_component_factors, mv_factor, mvs_bias_shift) + + # Then let's consider the maps to scalars. + self._init_scalars(s_factor) + + @staticmethod + def _compute_init_factors(initialization, gain, additional_factor, use_mv_heuristics): + """Computes prefactors for the initialization. + + See self.reset_parameters(). + """ + + if initialization not in {"default", "small", "unit_scalar", "almost_unit_scalar"}: + raise ValueError(f"Unknown initialization scheme {initialization}") + + if initialization == "default": + mv_factor = gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 0.0 + elif initialization == "small": + # Change scale by a factor of 0.3 in this layer + mv_factor = 0.1 * gain * additional_factor * np.sqrt(3) + s_factor = 0.1 * gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 0.0 + elif initialization == "unit_scalar": + # Change scale by a factor of 0.3 for MV outputs, and initialize bias around 1 + mv_factor = 0.1 * gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 1.0 + elif initialization == "almost_unit_scalar": + # Change scale by a factor of 0.3 for MV outputs, and initialize bias around 1 + mv_factor = 0.5 * gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 1.0 + else: + raise ValueError( + f"Unknown initialization scheme {initialization}, expected" + ' "default", "small", or "unit_scalar".' + ) + + # Individual factors for each multivector component + if use_mv_heuristics: + # Without corrections, the variance of standard normal inputs after a forward pass + # through this layer is different for each output grade. The reason is that the + # equivariance constraints affect different grades differently. + # We heuristically correct for this by initializing the weights for different basis + # elements differently, using the following additional factors on the weight bound: + # mv_component_factors = torch.sqrt(torch.Tensor([0.5, 4.0, 6.0, 4.0, 1.0, 0.5, 0.5])) + mv_component_factors = torch.sqrt( + torch.Tensor([1.0, 4.0, 6.0, 2.0, 0.5, 0.5, 1.5, 1.5, 0.5]) + ) + else: + mv_component_factors = torch.ones(NUM_PIN_LINEAR_BASIS_ELEMENTS) + return mv_component_factors, mv_factor, mvs_bias_shift, s_factor + + def _init_multivectors(self, mv_component_factors, mv_factor, mvs_bias_shift): + """Weight initialization for maps to multivector outputs.""" + + # We have + # `outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x]` + # The basis maps are more or less grade projections, summing over all basis elements + # corresponds to (almost) an identity map in the GA space. The sum over `b` and `x` thus + # does not contribute to `fan` substantially. (We may add a small ad-hoc factor later to + # make up for this approximation.) However, there is still the sum over incoming channels, + # and thus `fan ~ mv_in_channels`. Assuming (for now) that the previous layer contained a + # ReLU activation, we finally have the condition `Var[w] = 2 / mv_in_channels`. + # Since the variance of a uniform distribution between -a and a is given by + # `Var[Uniform(-a, a)] = a^2/3`, we should set `a = gain * sqrt(3 / mv_in_channels)`. + # In theory (see docstring). + fan_in = self._in_mv_channels + bound = mv_factor / np.sqrt(fan_in) + for i, factor in enumerate(mv_component_factors): + nn.init.uniform_(self.weight[..., i], a=-factor * bound, b=factor * bound) + + # Now let's focus on the scalar components of the multivector outputs. + # If there are only multivector inputs, all is good. But if scalar inputs contribute them as + # well, they contribute to the output variance as well. + # In this case, we initialize such that the multivector inputs and the scalar inputs each + # contribute half to the output variance. + # We can achieve this by inspecting the basis maps and seeing that only basis element 0 + # contributes to the scalar output. Thus, we can reduce the variance of the correponding + # weights to give a variance of 0.5, not 1. + if self.s2mvs is not None: + bound = mv_component_factors[0] * mv_factor / np.sqrt(fan_in) / np.sqrt(2) + nn.init.uniform_(self.weight[..., [0]], a=-bound, b=bound) + + # The same holds for the scalar-to-MV map, where we also just want a variance of 0.5. + if self.s2mvs is not None: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out( + self.s2mvs.weight + ) # pylint:disable=protected-access + fan_in = max(fan_in, 1) # Since in theory we could have 0-channel scalar "data" + bound = mv_component_factors[0] * mv_factor / np.sqrt(fan_in) / np.sqrt(2) + nn.init.uniform_(self.s2mvs.weight, a=-bound, b=bound) + + # Bias needs to be adapted, as the overall fan in is different (need to account for MV + # and s inputs) and we may need to account for the unit_scalar initialization scheme + if self.s2mvs.bias is not None: + fan_in = ( + nn.init._calculate_fan_in_and_fan_out(self.s2mvs.weight)[0] + + self._in_mv_channels + ) + bound = mv_component_factors[0] / np.sqrt(fan_in) if fan_in > 0 else 0 + nn.init.uniform_(self.s2mvs.bias, mvs_bias_shift - bound, mvs_bias_shift + bound) + + def _init_scalars(self, s_factor): + """Weight initialization for maps to multivector outputs.""" + + # If both exist, we need to account for overcounting again, and assign each a target a + # variance of 0.5. + models = [] + if self.s2s: + models.append(self.s2s) + if self.mvs2s: + models.append(self.mvs2s) + for model in models: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out( + model.weight + ) # pylint:disable=protected-access + fan_in = max(fan_in, 1) # Since in theory we could have 0-channel scalar "data" + bound = s_factor / np.sqrt(fan_in) / np.sqrt(len(models)) + nn.init.uniform_(model.weight, a=-bound, b=bound) + # Bias needs to be adapted, as the overall fan in is different (need to account for MV and + # s inputs) + if self.mvs2s and self.mvs2s.bias is not None: + fan_in = nn.init._calculate_fan_in_and_fan_out(self.mvs2s.weight)[ + 0 + ] # pylint:disable=protected-access + if self.s2s: + fan_in += nn.init._calculate_fan_in_and_fan_out(self.s2s.weight)[ + 0 + ] # pylint:disable=protected-access + bound = s_factor / np.sqrt(fan_in) if fan_in > 0 else 0 + nn.init.uniform_(self.mvs2s.bias, -bound, bound) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..748dc70faf9eaa7f5c4345b956a92c79079fadc0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .config import MLPConfig +from .geometric_bilinears import GeometricBilinear +from .mlp import GeoMLP +from .nonlinearities import ScalarGatedNonlinearity diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/config.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0eebccd677423ba87bb996ce340df84e326b8d92 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/config.py @@ -0,0 +1,43 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, List, Mapping, Optional + + +@dataclass +class MLPConfig: + """Geometric MLP configuration. + + Parameters + ---------- + mv_channels : iterable of int + Number of multivector channels at each layer, from input to output + s_channels : None or iterable of int + If not None, sets the number of scalar channels at each layer, from input to output. Length + needs to match mv_channels + activation : {"relu", "sigmoid", "gelu"} + Which (gated) activation function to use + dropout_prob : float or None + Dropout probability + """ + + mv_channels: Optional[List[int]] = None + s_channels: Optional[List[int]] = None + activation: str = "gelu" + dropout_prob: Optional[float] = None + + def __post_init__(self): + """Type checking / conversion.""" + if isinstance(self.dropout_prob, str) and self.dropout_prob.lower() in ["null", "none"]: + self.dropout_prob = None + + @classmethod + def cast(cls, config: Any) -> MLPConfig: + """Casts an object as MLPConfig.""" + if isinstance(config, MLPConfig): + return config + if isinstance(config, Mapping): + return cls(**config) + raise ValueError(f"Can not cast {config} to {cls}") diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/geometric_bilinears.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/geometric_bilinears.py new file mode 100644 index 0000000000000000000000000000000000000000..e51f53ee59fe90c43dbacdca827f814446b60527 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/geometric_bilinears.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Pin-equivariant geometric product layer between multivector tensors (torch.nn.Modules).""" + +from typing import Optional, Tuple + +import torch +from torch import nn + +from gatr.layers.linear import EquiLinear +from gatr.primitives import equivariant_join, geometric_product + + +class GeometricBilinear(nn.Module): + """Geometric bilinear layer. + + Pin-equivariant map between multivector tensors that constructs new geometric features via + geometric products and the equivariant join (based on a reference vector). + + Parameters + ---------- + in_mv_channels : int + Input multivector channels of `x` + out_mv_channels : int + Output multivector channels + hidden_mv_channels : int or None + Hidden MV channels. If None, uses out_mv_channels. + in_s_channels : int or None + Input scalar channels of `x`. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: Optional[int] = None, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + ) -> None: + super().__init__() + + # Default options + if hidden_mv_channels is None: + hidden_mv_channels = out_mv_channels + + out_mv_channels_each = hidden_mv_channels // 2 + assert ( + out_mv_channels_each * 2 == hidden_mv_channels + ), "GeometricBilinear needs even channel number" + + # Linear projections for GP + self.linear_left = EquiLinear( + in_mv_channels, + out_mv_channels_each, + in_s_channels=in_s_channels, + out_s_channels=None, + ) + self.linear_right = EquiLinear( + in_mv_channels, + out_mv_channels_each, + in_s_channels=in_s_channels, + out_s_channels=None, + initialization="almost_unit_scalar", + ) + + # Linear projections for join + self.linear_join_left = EquiLinear( + in_mv_channels, out_mv_channels_each, in_s_channels=in_s_channels, out_s_channels=None + ) + self.linear_join_right = EquiLinear( + in_mv_channels, out_mv_channels_each, in_s_channels=in_s_channels, out_s_channels=None + ) + + # Output linear projection + self.linear_out = EquiLinear( + hidden_mv_channels, out_mv_channels, in_s_channels, out_s_channels + ) + + def forward( + self, + multivectors: torch.Tensor, + reference_mv: torch.Tensor, + scalars: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : torch.Tensor with shape (..., in_s_channels) + Input scalars + reference_mv : torch.Tensor with shape (..., 16) + Reference multivector for equivariant join. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., self.out_mv_channels, 16) + Output multivectors + output_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars. + """ + + # GP + left, _ = self.linear_left(multivectors, scalars=scalars) + right, _ = self.linear_right(multivectors, scalars=scalars) + gp_outputs = geometric_product(left, right) + + # Equivariant join + left, _ = self.linear_join_left(multivectors, scalars=scalars) + right, _ = self.linear_join_right(multivectors, scalars=scalars) + join_outputs = equivariant_join(left, right, reference_mv) + + # Output linear + outputs_mv = torch.cat((gp_outputs, join_outputs), dim=-2) + outputs_mv, outputs_s = self.linear_out(outputs_mv, scalars=scalars) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/mlp.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..b226ff21f2b25a21c7ba76d226e2b54a759c5d83 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/mlp.py @@ -0,0 +1,101 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Factory functions for simple MLPs for multivector data.""" + +from typing import List, Tuple, Union + +import torch +from torch import nn + +from gatr.layers.dropout import GradeDropout +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.layers.mlp.geometric_bilinears import GeometricBilinear +from gatr.layers.mlp.nonlinearities import ScalarGatedNonlinearity + + +class GeoMLP(nn.Module): + """Geometric MLP. + + This is a core component of GATr's transformer blocks. It is similar to a regular MLP, except + that it uses geometric bilinears (GP and equivariant join) in place of the first linear layer. + + Assumes input has shape `(..., channels[0], 16)`, output has shape `(..., channels[-1], 16)`, + will create hidden layers with shape `(..., channel, 16)` for each additional entry in + `channels`. + + Parameters + ---------- + config: MLPConfig + Configuration object + """ + + def __init__( + self, + config: MLPConfig, + ) -> None: + super().__init__() + + # Store settings + self.config = config + + assert config.mv_channels is not None + s_channels = ( + [None for _ in config.mv_channels] if config.s_channels is None else config.s_channels + ) + + layers: List[nn.Module] = [] + + if len(config.mv_channels) >= 2: + layers.append( + GeometricBilinear( + in_mv_channels=config.mv_channels[0], + out_mv_channels=config.mv_channels[1], + in_s_channels=s_channels[0], + out_s_channels=s_channels[1], + ) + ) + if config.dropout_prob is not None: + layers.append(GradeDropout(config.dropout_prob)) + + for in_, out, in_s, out_s in zip( + config.mv_channels[1:-1], config.mv_channels[2:], s_channels[1:-1], s_channels[2:] + ): + layers.append(ScalarGatedNonlinearity(config.activation)) + layers.append(EquiLinear(in_, out, in_s_channels=in_s, out_s_channels=out_s)) + if config.dropout_prob is not None: + layers.append(GradeDropout(config.dropout_prob)) + + self.layers = nn.ModuleList(layers) + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor, reference_mv: torch.Tensor + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Forward pass. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors. + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars. + reference_mv : torch.Tensor with shape (..., 16) + Reference multivector for equivariant join. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors. + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + mv, s = multivectors, scalars + + for i, layer in enumerate(self.layers): + if i == 0: + mv, s = layer(mv, scalars=s, reference_mv=reference_mv) + else: + mv, s = layer(mv, scalars=s) + + return mv, s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/nonlinearities.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..2758002e706f3e999131f472fa8d688a38dcbdf6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/layers/mlp/nonlinearities.py @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives.nonlinearities import gated_gelu, gated_relu, gated_sigmoid + + +class ScalarGatedNonlinearity(nn.Module): + """Gated nonlinearity, where the gate is simply given by the scalar component of the input. + + Given multivector input x, computes f(x_0) * x, where f can either be ReLU, sigmoid, or GeLU. + + Auxiliary scalar inputs are simply processed with ReLU, sigmoid, or GeLU, without gating. + + Parameters + ---------- + nonlinearity : {"relu", "sigmoid", "gelu"} + Non-linearity type + """ + + def __init__(self, nonlinearity: str = "relu", **kwargs) -> None: + super().__init__() + + gated_fn_dict = dict(relu=gated_relu, gelu=gated_gelu, sigmoid=gated_sigmoid) + scalar_fn_dict = dict( + relu=nn.functional.relu, gelu=nn.functional.gelu, sigmoid=nn.functional.sigmoid + ) + try: + self.gated_nonlinearity = gated_fn_dict[nonlinearity] + self.scalar_nonlinearity = scalar_fn_dict[nonlinearity] + except KeyError as exc: + raise ValueError( + f"Unknown nonlinearity {nonlinearity} for options {list(gated_fn_dict.keys())}" + ) from exc + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes f(x_0) * x for multivector x, where f is GELU, ReLU, or sigmoid. + + f is chosen depending on self.nonlinearity. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., self.in_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., self.in_channels, self.in_scalars) + Input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., self.out_channels, 16) + Output multivectors + output_scalars : torch.Tensor with shape (..., self.out_channels, self.in_scalars) + Output scalars + """ + + gates = multivectors[..., [0]] + outputs_mv = self.gated_nonlinearity(multivectors, gates=gates) + outputs_s = self.scalar_nonlinearity(scalars) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7a87f16c013ed5b8018a4b9d51b53f9521f6b6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .axial_gatr import AxialGATr +from .gatr import GATr diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/axial_gatr.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/axial_gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..fa76bd7e826e8e9422aeaa692fcaef16bf173f2a --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/axial_gatr.py @@ -0,0 +1,253 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from dataclasses import replace +from typing import Optional, Tuple, Union + +import torch +from einops import rearrange +from torch import Tensor, nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.gatr_block import GATrBlock +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.tensors import construct_reference_multivector + +# Default rearrange patterns for odd blocks +_MV_REARRANGE_PATTERN = "... i j c x -> ... j i c x" +_S_REARRANGE_PATTERN = "... i j c -> ... j i c" + + +class AxialGATr(nn.Module): # pylint: disable=duplicate-code + """Axial GATr network for two token dimensions. + + This, together with gatr.nets.gatr.GATr, is the main architecture proposed in our paper. + + It combines `num_blocks` GATr transformer blocks, each consisting of geometric self-attention + layers, a geometric MLP, residual connections, and normalization layers. In addition, there + are initial and final equivariant linear layers. + + Assumes input data with shape `(..., num_items_1, num_items_2, num_channels, 16)`. + + The first, third, fifth, ... block computes attention over the `items_2` axis. The other blocks + compute attention over the `items_1` axis. Positional encoding can be specified separately for + both axes. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + hidden_mv_channels : int + Number of hidden multivector channels. + in_s_channels : None or int + If not None, sets the number of scalar input channels. + out_s_channels : None or int + If not None, sets the number of scalar output channels. + hidden_s_channels : None or int + If not None, sets the number of scalar hidden channels. + attention: Dict + Data for SelfAttentionConfig + mlp: Dict + Data for MLPConfig + num_blocks : int + Number of transformer blocks. + pos_encodings : tuple of bool + Whether to apply rotary positional embeddings along the item dimensions to the scalar keys + and queries. The first element in the tuple determines whether positional embeddings + are applied to the first item dimension, the second element the same for the second item + dimension. + collapse_dims : tuple of bool + Whether batch and token dimensions will be collapsed to support xformers block attention. + The first element of this tuple describes the behaviour in the 0th, 2nd, ... block, the + second element in the 1st, 3rd, ... block (where the axes are reversed). + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: int, + in_s_channels: Optional[int], + out_s_channels: Optional[int], + hidden_s_channels: Optional[int], + attention: SelfAttentionConfig, + mlp: MLPConfig, + num_blocks: int = 20, + checkpoint_blocks: bool = False, + pos_encodings: Tuple[bool, bool] = (False, False), + collapse_dims: Tuple[bool, bool] = (False, False), + **kwargs, + ) -> None: + super().__init__() + self.linear_in = EquiLinear( + in_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=hidden_s_channels, + ) + attention = SelfAttentionConfig.cast(attention) + mlp = MLPConfig.cast(mlp) + self.blocks = nn.ModuleList( + [ + GATrBlock( + mv_channels=hidden_mv_channels, + s_channels=hidden_s_channels, + attention=replace( + attention, + pos_encoding=pos_encodings[(block + 1) % 2], + ), + mlp=mlp, + ) + for block in range(num_blocks) + ] + ) + self.linear_out = EquiLinear( + hidden_mv_channels, + out_mv_channels, + in_s_channels=hidden_s_channels, + out_s_channels=out_s_channels, + ) + self._checkpoint_blocks = checkpoint_blocks + self._collapse_dims_for_even_blocks, self._collapse_dims_for_odd_blocks = collapse_dims + + def forward( + self, + multivectors: Tensor, + scalars: Optional[Tensor] = None, + attention_mask: Optional[Tuple] = None, + join_reference: Union[Tensor, str] = "data", + ) -> Tuple[Tensor, Optional[Tensor]]: + """Forward pass of the network. + + Parameters + ---------- + multivectors : Tensor with shape (..., num_items_1, num_items_2, in_mv_channels, 16) + Input multivectors. + scalars : None or Tensor with shape (..., num_items_1, num_items_2, in_s_channels) + Optional input scalars. + attention_mask : None or tuple of Tensor + Optional attention masks. + join_reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_1, num_items_2, out_mv_channels, 16) + Output multivectors. + outputs_s : None or Tensor with shape + (..., num_items_1, num_items_2, out_mv_channels, 16) + Output scalars, if scalars are provided. Otherwise None. + """ + + # Reference MV for equivariant join + reference_mv = construct_reference_multivector(join_reference, multivectors) + + # Pass through the blocks + h_mv, h_s = self.linear_in(multivectors, scalars=scalars) + for i, block in enumerate(self.blocks): + # For first, third, ... block, we want to perform attention over the first token + # dimension. We implement this by transposing the two item dimensions. + if i % 2 == 1: + h_mv, h_s, input_batch_dims = self._reshape_data_before_odd_blocks(h_mv, h_s) + else: + h_mv, h_s, input_batch_dims = self._reshape_data_before_even_blocks(h_mv, h_s) + + # Attention masks will also be different + if attention_mask is None: + this_attention_mask = None + else: + this_attention_mask = attention_mask[(i + 1) % 2] + + if self._checkpoint_blocks: + h_mv, h_s = checkpoint( + block, + h_mv, + use_reentrant=False, + scalars=h_s, + reference_mv=reference_mv, + attention_mask=this_attention_mask, + ) + else: + h_mv, h_s = block( + h_mv, + scalars=h_s, + reference_mv=reference_mv, + attention_mask=this_attention_mask, + ) + + # Transposing back to standard axis order + if i % 2 == 1: + h_mv, h_s = self._reshape_data_after_odd_blocks(h_mv, h_s, input_batch_dims) + else: + h_mv, h_s = self._reshape_data_after_even_blocks(h_mv, h_s, input_batch_dims) + + outputs_mv, outputs_s = self.linear_out(h_mv, scalars=h_s) + + return outputs_mv, outputs_s + + @staticmethod + def _construct_join_reference(inputs: Tensor): + """Constructs a reference vector for dualization from the inputs.""" + + # When using torch-geometric-style batching, this code should be adapted to perform the + # mean over the items in each batch, but not over the batch dimension. + # We leave this as an exercise for the practitioner :) + mean_dim = tuple(range(1, len(inputs.shape) - 1)) + return torch.mean(inputs, dim=mean_dim, keepdim=True) # (batch, 1, ..., 1, 16) + + def _reshape_data_before_odd_blocks(self, multivector, scalar): + # Transpose token axes + multivector = rearrange(multivector, _MV_REARRANGE_PATTERN) # (axis2, axis1, ...) + scalar = rearrange(scalar, _S_REARRANGE_PATTERN) # (axis2, axis1, ...) + + # Prepare uncollapsing + input_batch_dims = multivector.shape[:2] + assert scalar.shape[:2] == input_batch_dims + + # Collapse dimensions + if self._collapse_dims_for_odd_blocks: + multivector = multivector.reshape(-1, *multivector.shape[2:]) # (axis2 * axis1, ...) + scalar = scalar.reshape(-1, *scalar.shape[2:]) # (axis2 * axis1, ...) + + return multivector, scalar, input_batch_dims + + def _reshape_data_after_odd_blocks(self, multivector, scalar, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_odd_blocks: + multivector = multivector.reshape( + *input_batch_dims, *multivector.shape[1:] + ) # (axis2, axis1, ...) + scalar = scalar.reshape(*input_batch_dims, *scalar.shape[1:]) # (axis2, axis1, ...) + + # Re-transpose token axes + multivector = rearrange(multivector, _MV_REARRANGE_PATTERN) # (axis1, axis2, ...) + scalar = rearrange(scalar, _S_REARRANGE_PATTERN) # (axis1, axis2, ...) + + return multivector, scalar + + def _reshape_data_before_even_blocks(self, multivector, scalar): + # Prepare un-collapsing + input_batch_dims = multivector.shape[:2] + assert scalar.shape[:2] == input_batch_dims + + # Collapse + if self._collapse_dims_for_even_blocks: + multivector = multivector.reshape(-1, *multivector.shape[2:]) # (axis2 * axis1, ...) + scalar = scalar.reshape(-1, *scalar.shape[2:]) # (axis2 * axis1, ...) + + return multivector, scalar, input_batch_dims + + def _reshape_data_after_even_blocks(self, multivector, scalar, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_even_blocks: + multivector = multivector.reshape( + *input_batch_dims, *multivector.shape[1:] + ) # (axis2, axis1, ...) + scalar = scalar.reshape(*input_batch_dims, *scalar.shape[1:]) # (axis2, axis1, ...) + + return multivector, scalar diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/gatr.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc9381f4b8eecba7770f97f9ca88c574332562f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/nets/gatr.py @@ -0,0 +1,189 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant transformer for multivector data.""" + +from dataclasses import replace +from typing import Optional, Tuple, Union + +import torch +from torch import Tensor, nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.gatr_block import GATrBlock +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.tensors import construct_reference_multivector + + +class GATr(nn.Module): + """GATr network for a data with a single token dimension. + + This, together with gatr.nets.axial_gatr.AxialGATr, is the main architecture proposed in our + paper. + + It combines `num_blocks` GATr transformer blocks, each consisting of geometric self-attention + layers, a geometric MLP, residual connections, and normalization layers. In addition, there + are initial and final equivariant linear layers. + + Assumes input has shape `(..., items, in_channels, 16)`, output has shape + `(..., items, out_channels, 16)`, will create hidden representations with shape + `(..., items, hidden_channels, 16)`. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + hidden_mv_channels : int + Number of hidden multivector channels. + in_s_channels : None or int + If not None, sets the number of scalar input channels. + out_s_channels : None or int + If not None, sets the number of scalar output channels. + hidden_s_channels : None or int + If not None, sets the number of scalar hidden channels. + attention: Dict + Data for SelfAttentionConfig + mlp: Dict + Data for MLPConfig + num_blocks : int + Number of transformer blocks. + dropout_prob : float or None + Dropout probability + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: int, + in_s_channels: Optional[int], + out_s_channels: Optional[int], + hidden_s_channels: Optional[int], + attention: SelfAttentionConfig, + mlp: MLPConfig, + num_blocks: int = 10, + reinsert_mv_channels: Optional[Tuple[int]] = None, + reinsert_s_channels: Optional[Tuple[int]] = None, + checkpoint_blocks: bool = False, + dropout_prob: Optional[float] = None, + **kwargs, + ) -> None: + super().__init__() + self.linear_in = EquiLinear( + in_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=hidden_s_channels, + ) + attention = replace( + SelfAttentionConfig.cast(attention), # convert duck typing to actual class + additional_qk_mv_channels=0 + if reinsert_mv_channels is None + else len(reinsert_mv_channels), + additional_qk_s_channels=0 if reinsert_s_channels is None else len(reinsert_s_channels), + ) + mlp = MLPConfig.cast(mlp) + self.blocks = nn.ModuleList( + [ + GATrBlock( + mv_channels=hidden_mv_channels, + s_channels=hidden_s_channels, + attention=attention, + mlp=mlp, + dropout_prob=dropout_prob, + ) + for _ in range(num_blocks) + ] + ) + self.linear_out = EquiLinear( + hidden_mv_channels, + out_mv_channels, + in_s_channels=hidden_s_channels, + out_s_channels=out_s_channels, + ) + self._reinsert_s_channels = reinsert_s_channels + self._reinsert_mv_channels = reinsert_mv_channels + self._checkpoint_blocks = checkpoint_blocks + + def forward( + self, + multivectors: torch.Tensor, + scalars: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + join_reference: Union[Tensor, str] = "data", + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Forward pass of the network. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors. + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars. + attention_mask: None or torch.Tensor with shape (..., num_items, num_items) + Optional attention mask + join_reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors. + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + # Reference multivector and channels that will be re-inserted in any query / key computation + reference_mv = construct_reference_multivector(join_reference, multivectors) + additional_qk_features_mv, additional_qk_features_s = self._construct_reinserted_channels( + multivectors, scalars + ) + + # Pass through the blocks + h_mv, h_s = self.linear_in(multivectors, scalars=scalars) + for block in self.blocks: + if self._checkpoint_blocks: + h_mv, h_s = checkpoint( + block, + h_mv, + use_reentrant=False, + scalars=h_s, + reference_mv=reference_mv, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + else: + h_mv, h_s = block( + h_mv, + scalars=h_s, + reference_mv=reference_mv, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + + outputs_mv, outputs_s = self.linear_out(h_mv, scalars=h_s) + + return outputs_mv, outputs_s + + def _construct_reinserted_channels(self, multivectors, scalars): + """Constructs input features that will be reinserted in every attention layer.""" + + if self._reinsert_mv_channels is None: + additional_qk_features_mv = None + else: + additional_qk_features_mv = multivectors[..., self._reinsert_mv_channels, :] + + if self._reinsert_s_channels is None: + additional_qk_features_s = None + else: + assert scalars is not None + additional_qk_features_s = scalars[..., self._reinsert_s_channels] + + return additional_qk_features_mv, additional_qk_features_s diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cecd4e22ec689722aadf06c347081b6c60e054ec --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .attention import geometric_attention, pga_attention, sdp_attention +from .bilinear import geometric_product, outer_product +from .dropout import grade_dropout +from .dual import dual, equivariant_join +from .invariants import inner_product, norm, pin_invariants +from .linear import ( + NUM_PIN_LINEAR_BASIS_ELEMENTS, + equi_linear, + grade_involute, + grade_project, + reverse, +) +from .nonlinearities import gated_gelu, gated_gelu_divide, gated_relu, gated_sigmoid +from .normalization import equi_layer_norm diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/attention.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..0579a23330ef678ee6ea68400b2d775976f45eb1 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/attention.py @@ -0,0 +1,453 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import math +from functools import lru_cache +from typing import Callable, Optional, Tuple, Union + +import numpy as np +import torch +from einops import rearrange +from torch import Tensor +from torch.nn.functional import scaled_dot_product_attention as torch_sdpa +# from xformers.ops import AttentionBias, memory_efficient_attention + +from gatr.primitives.dual import join_norm +from gatr.primitives.invariants import inner_product +from gatr.utils.einsum import cached_einsum +from gatr.utils.tensors import expand_pairwise, to_nd + +# When computing the normalization factor in attention weights, multivectors contribute with the +# following factor: +_MV_SIZE_FACTOR = 8 + +# Multivector indices that contribute to inner product and trivectors +# All components that contribute to the inner product: +_INNER_PRODUCT_IDX = [0, 2, 3, 4, 8, 9, 10, 14] +# Scalar, non-ideal part of vector and bivector; no trivectors: +_INNER_PRODUCT_WO_TRI_IDX = [0, 2, 3, 4, 8, 9, 10] +# Trivector indices (ideal part first): +_TRIVECTOR_IDX = [11, 12, 13, 14] + +# Masked out attention logits are set to this constant (a finite replacement for -inf): +_MASKED_OUT = float("-inf") + +# Force the use of xformers attention, even when no xformers attention mask is provided: +# FORCE_XFORMERS = False + + +def sdp_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., num_items_in, num_s_channels_out) + Values, scalar part. + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_out, num_mv_channels_out, 16) + Result, multivector part + outputs_s : Tensor with shape (..., num_items_out, num_s_channels_out) + Result, scalar part + """ + + # Construct queries and keys by concatenating relevant MV components and aux scalars + q = torch.cat([rearrange(q_mv[..., _INNER_PRODUCT_IDX], "... c x -> ... (c x)"), q_s], -1) + k = torch.cat([rearrange(k_mv[..., _INNER_PRODUCT_IDX], "... c x -> ... (c x)"), k_s], -1) + + num_channels_out = v_mv.shape[-2] + v = torch.cat([rearrange(v_mv, "... c x -> ... (c x)"), v_s], -1) + + v_out = scaled_dot_product_attention(q, k, v) + + v_out_mv = rearrange(v_out[..., : num_channels_out * 16], "... (c x) -> ... c x", x=16) + v_out_s = v_out[..., num_channels_out * 16 :] + + return v_out_mv, v_out_s + + +def pga_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, + weights: Optional[Tuple[Tensor, Tensor, Tensor]] = None, + attention_mask=None, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products and the equivariant join. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + norm(join(q_mv[..., i, :, :], k_mv[..., j, :, :])) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Optionally, the three contributions are weighted with `weights`. + + This is not used in GATr, because it does not reduce to dot-product attention and thus does not + benefit from efficient implementations like `geometric_attention()` does. + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., num_items_in, num_s_channels_out) + Values, scalar part. + weights : None, or tuple of three Tensors + Weights for the combination of the inner product, join, and aux scalar parts + attention_mask: None or Tensor with shape (..., num_items, num_items) + Optional attention mask + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_out, num_mv_channels_out, 16) + Result, multivector part. + outputs_s : Tensor with shape (..., num_items_out, num_s_channels_out) + Result, scalar part. + """ + + # Negative weights are trouble + if weights is not None: + for weight in weights: + assert torch.min(weight) >= 0.0 + + # Compute attention weights, first through the inner product between multivectors... + q_mv = rearrange(q_mv, "... items_out channels x -> ... items_out 1 channels x") + k_mv = rearrange(k_mv, "... items_in channels x -> ... 1 items_in channels x") + h = inner_product(q_mv, k_mv)[..., 0] # (..., items_out, items_in, channels) + if weights is not None: + h = weights[0] * h + attn_weights = torch.sum(h, dim=-1) # (..., items_out, items_in) + + # ... then through the join... + h = -join_norm( + q_mv, k_mv, channel_sum=True, channel_weights=weights[1] if weights is not None else None + )[ + ..., 0 + ] # (..., items_out, items_in) + attn_weights = attn_weights + h + + # ... and finally from auxiliary scalars + q_s = rearrange(q_s, "... items_out channels -> ... items_out 1 channels") + k_s = rearrange(k_s, "... items_in channels -> ... 1 items_in channels") + h = q_s * k_s # (..., items_out, items_in, channels) + if weights is not None: + h = weights[2] * h + attn_weights = attn_weights + torch.sum(h, dim=-1) # (..., items_out, items_in) + + # Attention mask + if attention_mask is not None: + attn_weights.masked_fill_(~attention_mask, _MASKED_OUT) + + # Combine and weight + attn_weights = attn_weights / np.sqrt(2 * q_mv.shape[-2] * _MV_SIZE_FACTOR + q_s.shape[-1]) + + # Softmax + attn_weights = attn_weights.softmax(dim=-1) # Softmax over items_in + + # Compute attention output + outputs_mv = cached_einsum( + "... j i, ... i c x -> ... j c x", attn_weights, v_mv + ) # (..., items_out, channels, 16) + outputs_s = cached_einsum( + "... j i, ... i c -> ... j c", attn_weights, v_s + ) # (..., items_out, channels) + + return outputs_mv, outputs_s + + +@lru_cache() +def _build_dist_basis(device, dtype) -> Tuple[Tensor, Tensor]: + """Compute basis features for queries and keys in the geometric SDP attention. + + Parameters + ---------- + device: torch.device + Device. + dtype: torch.dtype + Dtype. + + Returns + ------- + basis_q : Tensor with shape (4, 4, 5) + Basis features for queries. + basis_k : Tensor with shape (4, 4, 5) + Basis features for keys. + """ + r3 = torch.arange(3, device=device) + basis_q = torch.zeros((4, 4, 5), device=device, dtype=dtype) + basis_k = torch.zeros((4, 4, 5), device=device, dtype=dtype) + + # -sum_i (q_i^2) * k_0^2 + basis_q[r3, r3, 0] = 1 + basis_k[3, 3, 0] = -1 + + # -q_0^2 * sum_i (k_i^2) + basis_q[3, 3, 1] = 1 + basis_k[r3, r3, 1] = -1 + + # sum_i 2 q_0 q_i k_0 k_i + basis_q[r3, 3, 2 + r3] = 1 + basis_k[r3, 3, 2 + r3] = 2 + + return basis_q, basis_k + + +def _build_dist_vec(tri: Tensor, basis: Tensor, normalizer: Callable[[Tensor], Tensor]) -> Tensor: + """Build 5D vector whose inner product with another such vector computes the squared distance. + + Parameters + ---------- + tri: Tensor + Batch of multivectors, only trivector part is used. + basis: Tensor + One of the bases from _build_dist_basis. + normalizer: Callable[[Tensor], Tensor] + A normalization function. + + Returns + ------- + outputs : Tensor + Batch of 5D vectors + """ + tri_normed = tri * normalizer(tri[..., [3]]) + vec = cached_einsum("xyz,... x,... y->... z", basis, tri_normed, tri_normed) + return vec + + +def lin_square_normalizer(v: Tensor, epsilon=0.001) -> Tensor: + """Apply linear square normalization to the input tensor. + + Parameters + ---------- + v : Tensor + Input tensor. + epsilon : float, optional + Small constant added to the denominator to avoid division by zero. + Default is 0.001. + + Returns + ------- + normalized_v : Tensor + Normalized tensor after applying linear square normalization. + """ + return v / (v.pow(2) + epsilon) + + +def geometric_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, + normalizer: Callable[[Tensor], Tensor], + weights: Optional[Tensor] = None, + attn_mask: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products and nonlinear aux features. + + This is the main attention mechanism used in GATr. Thanks to the nonlinear features, the + scaled-dot-product attention takes into account the Euclidean distance. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + + inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Optionally, the three contributions are weighted with `weights`. + + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + normalizer : callable + Normalization function. + weights: Optional[Tensor] with shape (..., 1, num_channels_in) + Weights for the combination of the inner product, nonlinear distance-aware features, and + scalar parts. + attn_mask: Optional[Tensor] with shape (..., num_items_in, num_items_out) + Optional attention mask + + Returns + ------- + outputs_mv : Tensor with shape (..., heads, num_items_out, num_channels_out, 16) + Result, multivector part. + outputs_s : Tensor with shape (..., heads, num_items_out, num_s_channels_out) + Result, scalar part. + """ + bh_shape = q_mv.shape[:-3] + q_mv = to_nd(q_mv, 5) + k_mv = to_nd(k_mv, 5) + v_mv = to_nd(v_mv, 5) + q_s = to_nd(q_s, 4) + k_s = to_nd(k_s, 4) + v_s = to_nd(v_s, 4) + + num_mv_channels_v = v_mv.shape[-2] + num_s_channels_v = v_s.shape[-1] + num_mv_channels_qk = q_mv.shape[-2] + num_s_channels_qk = q_s.shape[-1] + + q_tri = q_mv[..., _TRIVECTOR_IDX] + k_tri = k_mv[..., _TRIVECTOR_IDX] + + basis_q, basis_k = _build_dist_basis(q_tri.device, q_tri.dtype) + + q_dist = _build_dist_vec(q_tri, basis_q, normalizer) + k_dist = _build_dist_vec(k_tri, basis_k, normalizer) + if weights is not None: + q_dist = q_dist * weights[..., None].to(q_dist.dtype) + + device = q_mv.device + dtype = q_mv.dtype + + num_channels_qk = num_mv_channels_qk * (7 + 5) + num_s_channels_qk + num_channels_v = num_mv_channels_v * 16 + num_s_channels_v + num_channels = max(num_channels_qk, num_channels_v) + num_channels = 8 * -(-num_channels // 8) # Ceil to multiple of 8 + + q = torch.cat( + [ + rearrange(q_mv[..., _INNER_PRODUCT_WO_TRI_IDX], "... c x -> ... (c x)"), + rearrange(q_dist, "... c d -> ... (c d)"), + q_s, + torch.zeros(*q_s.shape[:3], num_channels - num_channels_qk, device=device, dtype=dtype), + ], + -1, + ) + k = torch.cat( + [ + rearrange(k_mv[..., _INNER_PRODUCT_WO_TRI_IDX], "... c x -> ... (c x)"), + rearrange(k_dist, "... c d -> ... (c d)"), + k_s, + torch.zeros(*k_s.shape[:3], num_channels - num_channels_qk, device=device, dtype=dtype), + ], + -1, + ) + + v = torch.cat( + [ + rearrange(v_mv, "... c x -> ... (c x)"), + v_s, + torch.zeros(*v_s.shape[:3], num_channels - num_channels_v, device=device, dtype=dtype), + ], + -1, + ) + + k = k * math.sqrt(num_channels / num_channels_qk) # Correct for zero padding + q, k, v = expand_pairwise(q, k, v, exclude_dims=(-2,)) # Don't expand along token dimension + v_out = scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + + v_out_mv = rearrange(v_out[..., : num_mv_channels_v * 16], "... (c x) -> ... c x", x=16) + v_out_s = v_out[..., num_mv_channels_v * 16 : num_mv_channels_v * 16 + num_s_channels_v] + + v_out_mv = v_out_mv.view(*bh_shape, *v_out_mv.shape[-3:]) + v_out_s = v_out_s.view(*bh_shape, *v_out_s.shape[-2:]) + + return v_out_mv, v_out_s + + +def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + # attn_mask: Optional[Union[AttentionBias, Tensor]] = None, + attn_mask: Optional[Tensor] = None, +) -> Tensor: + """Execute (vanilla) scaled dot-product attention. + + Dynamically dispatch to xFormers if attn_mask is an instance of xformers.ops.AttentionBias + or FORCE_XFORMERS is set, use torch otherwise. + + Parameters + ---------- + query : Tensor + of shape [batch, head, item, d] + key : Tensor + of shape [batch, head, item, d] + value : Tensor + of shape [batch, head, item, d] + attn_mask : Optional[Union[AttentionBias, Tensor]] + Attention mask + + Returns + ------- + Tensor + of shape [batch, head, item, d] + """ + # if FORCE_XFORMERS or isinstance(attn_mask, AttentionBias): + # query = query.transpose(1, 2) # [batch, head, item, d] -> [batch, item, head, d] + # key = key.transpose(1, 2) + # value = value.transpose(1, 2) + # out = memory_efficient_attention( + # query.contiguous(), key.contiguous(), value, attn_bias=attn_mask + # ) + # out = out.transpose(1, 2) # [batch, item, head, d] -> [batch, head, item, d] + # return out + return torch_sdpa(query, key, value, attn_mask=attn_mask) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/bilinear.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/bilinear.py new file mode 100644 index 0000000000000000000000000000000000000000..da42aedd1bc0700cd2f7fe346c979137e6795243 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/bilinear.py @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache +from pathlib import Path + +import torch + +from gatr.utils.einsum import cached_einsum + +_FILENAMES = {"gp": "geometric_product.pt", "outer": "outer_product.pt"} + + +@lru_cache() +def _load_bilinear_basis( + kind: str, device=torch.device("cpu"), dtype=torch.float32 +) -> torch.Tensor: + """Loads basis elements for Pin-equivariant bilinear maps between multivectors. + + This function is cached. + + Parameters + ---------- + kind : {"gp", "outer"} + Filename of the basis file, assumed to be found in __file__ / data + device : torch.Device or str + Device + dtype : torch.Dtype + Data type + + Returns + ------- + basis : torch.Tensor with shape (num_basis_elements, 16, 16, 16) + Basis elements for bilinear equivariant maps between multivectors. + """ + + # To avoid duplicate loading, base everything on float32 CPU version + if device not in [torch.device("cpu"), "cpu"] and dtype != torch.float32: + basis = _load_bilinear_basis(kind) + else: + filename = Path(__file__).parent.resolve() / "data" / _FILENAMES[kind] + sparse_basis = torch.load(filename).to(torch.float32) + # Convert to dense tensor + # The reason we do that is that einsum is not defined for sparse tensors + basis = sparse_basis.to_dense() + + return basis.to(device=device, dtype=dtype) + + +def geometric_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Computes the geometric product f(x,y) = xy. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x, y, and coeffs. + """ + + # Select kernel on correct device + gp = _load_bilinear_basis("gp", device=x.device, dtype=x.dtype) + + # Compute geometric product + outputs = cached_einsum("i j k, ... j, ... k -> ... i", gp, x, y) + + return outputs + + +def outer_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Computes the outer product `f(x,y) = x ^ y`. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x, y, and coeffs. + """ + + # Select kernel on correct device + op = _load_bilinear_basis("outer", device=x.device, dtype=x.dtype) + + # Compute geometric product + outputs = cached_einsum("i j k, ... j, ... k -> ... i", op, x, y) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/geometric_product.pt b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/geometric_product.pt new file mode 100644 index 0000000000000000000000000000000000000000..902ee9d75eacab253dbbab54b406b563a9a88e99 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/geometric_product.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eb08e81346400f8081443b935b9cd38d9589fa89d522a7fe08a56ea9b6bce5f +size 5967 diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/outer_product.pt b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/outer_product.pt new file mode 100644 index 0000000000000000000000000000000000000000..d805dec4c667b545deaba1d09edd828c37868802 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/data/outer_product.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a23738415b7ab0c5dbbd749a14e7a137f3f888e0869e0b01c882b9113781e8b +size 3135 diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dropout.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..4b22d8f01daeeaf72b00195398b9bc35677985f7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dropout.py @@ -0,0 +1,38 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.primitives.linear import grade_project + + +def grade_dropout(x: torch.Tensor, p: float, training: bool = True) -> torch.Tensor: + """Multivector dropout, dropping out grades independently. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input data. + p : float + Dropout probability (assumed the same for each grade). + training : bool + Switches between train-time and test-time behaviour. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Inputs with dropout applied. + """ + + # Project to grades + x = grade_project(x) + + # Apply standard 1D dropout + # For whatever reason, that only works with a single batch dimension, so let's reshape a bit + h = x.view(-1, 5, 16) + h = torch.nn.functional.dropout1d(h, p=p, training=training, inplace=False) + h = h.view(x.shape) + + # Combine grades again + h = torch.sum(h, dim=-2) + + return h diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dual.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dual.py new file mode 100644 index 0000000000000000000000000000000000000000..22a542cb2de831fa847fbe109f641348fc878cdd --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/dual.py @@ -0,0 +1,303 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache +from itertools import product +from typing import Tuple + +import torch + +from gatr.primitives.bilinear import outer_product +from gatr.utils.einsum import cached_einsum + +# Flag which reference join implementations we're using +_USE_EFFICIENT_JOIN = True + + +@lru_cache() +@torch.no_grad() +def _compute_dualization( + device=torch.device("cpu"), dtype=torch.float32 +) -> Tuple[torch.Tensor, torch.Tensor]: + """Constructs a tensor for the dual operation. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + permutation : list of int + Permutation index list to compute the dual + factors : torch.Tensor + Signs to multiply the dual outputs with. + """ + permutation = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + factors = torch.tensor( + [1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1], device=device, dtype=dtype + ) + return permutation, factors + + +@lru_cache() +@torch.no_grad() +def _compute_efficient_join(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a kernel for the join operation. + + The kernel is such that join(x, y)_i = einsum(kernel_ijk, x_j, x_k). + + For now, we do this in the simplest possible way: by computing the joins between two sets of + basis vectors. (Since the join is bilinear, that should be enough.) + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + kernel : torch.Tensor + Joint kernel + """ + + kernel = torch.zeros((16, 16, 16), dtype=dtype, device=device) + + for i in range(16): + for j in range(16): + x, y = torch.zeros(16, dtype=dtype, device=device), torch.zeros( + 16, dtype=dtype, device=device + ) + x[i] = 1.0 + y[j] = 1.0 + kernel[:, i, j] = dual(outer_product(dual(x), dual(y))) + + return kernel + + +@lru_cache() +@torch.no_grad() +def _compute_join_norm_idx(threshold=0.5) -> Tuple[list, list, list]: + """Constructs everything we need to compute norm(equi_norm(x,y)) in a memory-efficient way. + + Parameters + ---------- + threshold : float + Threshold that determines discretization of join kernel + + Returns + ------- + left_idx : list of list of int + List (output components) of list (contributing terms) of indices of x + left_idx : list of list of int + List (output components) of list (contributing terms) of indices of y + left_idx : list of list of float + List (output components) of list (contributing terms) of indices of y + """ + + # Get join kernel K_ijk + join_kernel = _compute_efficient_join() + + # Output components that contribute to the norm: all e_{i...k} without a 0 in the idx + output_idx = [0, 2, 3, 4, 8, 9, 10, 14] + + # Identify input idx that contribute to those output idx, with the corresponding signs + all_left_idx = [] + all_right_idx = [] + all_signs = [] + + for i in output_idx: + left_idx = [] + right_idx = [] + signs = [] + + for j, k in product(range(16), repeat=2): + if join_kernel[i, j, k] > threshold: + left_idx.append(j) + right_idx.append(k) + signs.append(1.0) + elif join_kernel[i, j, k] < -threshold: + left_idx.append(j) + right_idx.append(k) + signs.append(-1.0) + + all_left_idx.append(left_idx) + all_right_idx.append(right_idx) + all_signs.append(signs) + + return all_left_idx, all_right_idx, all_signs + + +def dual(x: torch.Tensor) -> torch.Tensor: + """Computes the dual of `inputs` (non-equivariant!). + + See Table 4 in the reference. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector, of which we want to compute the dual. + + Returns + ------- + outputs : torch.Tensor with shale (..., 16) + The dual of `inputs`, using the pseudoscalar component of `reference` as basis. + """ + + # Select factors on correct device + perm, factors = _compute_dualization(x.device, x.dtype) + + # Compute dual + result = factors * x[..., perm] + + return result + + +def equivariant_join(x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor) -> torch.Tensor: + """Computes the equivariant join. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + This function uses either explicit_equivariant_join or efficient_equivariant_join, depending + on whether _USE_EFFICIENT_JOIN is set. + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Equivariant join result. + """ + + if _USE_EFFICIENT_JOIN: + return efficient_equivariant_join(x, y, reference) + + return explicit_equivariant_join(x, y, reference) + + +def explicit_equivariant_join( + x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor +) -> torch.Tensor: + """Computes the equivariant join, using the explicit, but slow, implementation. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Rquivariant join result. + """ + return reference[..., [14]] * dual(outer_product(dual(x), dual(y))) + + +def efficient_equivariant_join( + x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor +) -> torch.Tensor: + """Computes the equivariant join, using the efficient implementation. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Rquivariant join result. + """ + + kernel = _compute_efficient_join(x.device, x.dtype) + return reference[..., [14]] * cached_einsum("i j k , ... j, ... k -> ... i", kernel, x, y) + + +def join_norm( + x: torch.Tensor, y: torch.Tensor, square=False, channel_sum=False, channel_weights=None +) -> torch.Tensor: + """Computes the norm of the join, `|join(x,y)|`, in a single operation. + + Optionally: + - computes the squared norm instead of the norm (when `square = True`), + - sums over channels, meaning the second-to-last dimension (when `channel_sum = True`) + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Left input + y : torch.Tensor with shape (..., 16) + Right input + square : bool + If True, computes the squared norm rather than the norm + channel_sum : bool + If True, sums the result over channels (before taking the square root). We assume channels + correspond to the second-to-last dimension of the input tensors. + channel_weights : None torch.Tensor with shape (..., num_channels) + If channel_sum is True, a non-None value of channel_weights weighs the different channels + before summing over them. (Note that we do not perform any normalization here.) + + Returns + ------- + norm : torch.Tensor with shape (..., 1) + Norm of join + """ + + # Prepare computation + output = 0.0 + all_left_idx, all_right_idx, all_signs = _compute_join_norm_idx() + + # Sum over all contributing terms + for left_idx, right_idx, signs in zip(all_left_idx, all_right_idx, all_signs): + # Compute contribution + component = 0.0 + for j, k, sign in zip(left_idx, right_idx, signs): + component = component + sign * x[..., j] * y[..., k] + component = component**2 + + # Compute channel sum if desired + if channel_sum: + if channel_weights is not None: + component = component * channel_weights + component = component.sum(dim=-1) + + output = output + component + + # Square root, unless the square norm is computed + if not square: + output = torch.sqrt(output) + + return output.unsqueeze(-1) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/invariants.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/invariants.py new file mode 100644 index 0000000000000000000000000000000000000000..70a25fcd8e31121554cbf6c8d8df132c92533d51 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/invariants.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import torch +import torch.linalg + +from gatr.primitives.bilinear import _load_bilinear_basis +from gatr.primitives.linear import _compute_reversal, grade_project +from gatr.utils.einsum import cached_einsum + + +@lru_cache() +def compute_inner_product_mask(device=torch.device("cpu")) -> torch.Tensor: + """Constructs a bool array for the inner product calculation. + + The inner product of MVs is <~x y>_0, i.e. take the grade-0 component of the geometric + product of the reverse of x with y. + Both the scalar component of the GP, and the reversal matrix, are diagonal. + Their product is 0 for basis elements involving e0, and 1 elsewhere, i.e. + IP = [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0] + for dim order '', 'e0', 'e1', 'e2', 'e3', 'e01', 'e02', 'e03', 'e12', 'e13', 'e23', + 'e012', 'e013', 'e023', 'e123', 'e0123' + + Parameters + ---------- + device : torch.device + Device + + Returns + ------- + ip_mask : torch.Tensor with shape (16,) + Inner product mask + """ + gp = _load_bilinear_basis("gp", device=device, dtype=torch.float32) + inner_product_mask = torch.diag(gp[0]) * _compute_reversal(device=device, dtype=torch.float32) + return inner_product_mask.bool() + +def inner_product(x: torch.Tensor, y: torch.Tensor, channel_sum: bool = False) -> torch.Tensor: + """Computes the inner product of multivectors f(x,y) = = <~x y>_0. + + In addition to summing over the 16 multivector dimensions, this function also sums + over an additional channel dimension if channel_sum == True. + + Equal to `geometric_product(reverse(x), y)[..., [0]]` (but faster). + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) or (..., channels, 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) or (..., channels, 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + channel_sum: bool + Whether to sum over the second-to-last axis (channels) + + Returns + ------- + outputs : torch.Tensor with shape (..., 1) + Result. Batch dimensions are result of broadcasting between x and y. + """ + + x = x[..., compute_inner_product_mask(device=x.device)] + y = y[..., compute_inner_product_mask(device=x.device)] + + if channel_sum: + outputs = cached_einsum("... c i, ... c i -> ...", x, y) + else: + outputs = cached_einsum("... i, ... i -> ...", x, y) + + # We want the output to have shape (..., 1) + outputs = outputs.unsqueeze(-1) + + return outputs + + +def norm(x: torch.Tensor) -> torch.Tensor: + """Computes the GA norm of an input multivector. + + Equal to sqrt(inner_product(x, x)). + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 1) + Geometric algebra norm of x. + """ + return torch.linalg.norm(x[..., compute_inner_product_mask(device=x.device)], dim=-1, keepdim=True) # torch.linalg.norm is faster than the einsum version below + # return torch.sqrt(torch.clamp(inner_product(x, x), 0.0)) + +def pin_invariants(x: torch.Tensor) -> torch.Tensor: + """Computes five invariants from multivectors: scalar component, norms of the four other grades. + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 5) + Invariants computed from input multivectors + """ + + # Project to grades + projections = grade_project(x) # (..., 5, 16) + + # Compute norms + squared_norms = inner_product(projections, projections)[..., 0] # (..., 5) + norms = torch.sqrt(torch.clamp(squared_norms, 0.0)) + + # Outputs: scalar component of input and norms of four other grades + return torch.cat((x[..., [0]], norms[..., 1:]), dim=-1) # (..., 5) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/linear.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a50df0bf0f9e9e324008833333f720df1d3b1b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/linear.py @@ -0,0 +1,201 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import torch + +from gatr.utils.einsum import cached_einsum, custom_einsum + + +@lru_cache() +def _compute_pin_equi_linear_basis( + device=torch.device("cpu"), dtype=torch.float32, normalize=True +) -> torch.Tensor: + """Constructs basis elements for Pin(3,0,1)-equivariant linear maps between multivectors. + + This function is cached. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + normalize : bool + Whether to normalize the basis elements + + Returns + ------- + basis : torch.Tensor with shape (7, 16, 16) + Basis elements for equivariant linear maps. + """ + + # We constructed these manually in a notebook, here hardcoded for convenience + basis_elements = [ + [0], + [1, 2, 3, 4], + [5, 6, 7, 8, 9, 10], + [11, 12, 13, 14], + [15], + [(1, 0)], + [(5, 2), (6, 3), (7, 4)], + [(11, 8), (12, 9), (13, 10)], + [(15, 14)], + ] + basis = [] + + for elements in basis_elements: + w = torch.zeros((16, 16)) + for element in elements: + try: + i, j = element + w[i, j] = 1.0 + except TypeError: + w[element, element] = 1.0 + + if normalize: + w /= torch.linalg.norm(w) + + w = w.unsqueeze(0) + basis.append(w) + + catted_basis = torch.cat(basis, dim=0) + + return catted_basis.to(device=device, dtype=dtype) + + +@lru_cache() +def _compute_reversal(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a matrix that computes multivector reversal. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + reversal_diag : torch.Tensor with shape (16,) + The diagonal of the reversal matrix, consisting of +1 and -1 entries. + """ + reversal_flat = torch.ones(16, device=device, dtype=dtype) + reversal_flat[5:15] = -1 + return reversal_flat + + +@lru_cache() +def _compute_grade_involution(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a matrix that computes multivector grade involution. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + involution_diag : torch.Tensor with shape (16,) + The diagonal of the involution matrix, consisting of +1 and -1 entries. + """ + involution_flat = torch.ones(16, device=device, dtype=dtype) + involution_flat[1:5] = -1 + involution_flat[11:15] = -1 + return involution_flat + + +NUM_PIN_LINEAR_BASIS_ELEMENTS = len(_compute_pin_equi_linear_basis()) + + +def equi_linear(x: torch.Tensor, coeffs: torch.Tensor) -> torch.Tensor: + """Pin-equivariant linear map f(x) = sum_{a,j} coeffs_a W^a_ij x_j. + + The W^a are seven pre-defined basis elements. + + Parameters + ---------- + x : torch.Tensor with shape (..., in_channels, 16) + Input multivector. Batch dimensions must be broadcastable between x and coeffs. + coeffs : torch.Tensor with shape (out_channels, in_channels, 7) + Coefficients for the 59 basis elements. Batch dimensions must be broadcastable between x and + coeffs. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x and coeffs. + """ + basis = _compute_pin_equi_linear_basis(device=x.device, dtype=x.dtype) + # return custom_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x, path=[0, 1, 0, 1]) + return cached_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x) + +def grade_project(x: torch.Tensor) -> torch.Tensor: + """Projects an input tensor to the individual grades. + + The return value is a single tensor with a new grade dimension. + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 5, 16) + Output multivector. The second-to-last dimension indexes the grades. + """ + + # Select kernel on correct device + basis = _compute_pin_equi_linear_basis(device=x.device, dtype=x.dtype, normalize=False) + + # First five basis elements are grade projections + basis = basis[:5] + + # Project to grades + projections = cached_einsum("g i j, ... j -> ... g i", basis, x) + + return projections + + +def reverse(x: torch.Tensor) -> torch.Tensor: + """Computes the reversal of a multivector. + + The reversal has the same scalar, vector, and pseudoscalar components, but flips sign in the + bivector and trivector components. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivector. + """ + return _compute_reversal(device=x.device, dtype=x.dtype) * x + + +def grade_involute(x: torch.Tensor) -> torch.Tensor: + """Computes the grade involution of a multivector. + + The reversal has the same scalar, bivector, and pseudoscalar components, but flips sign in the + vector and trivector components. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivector. + """ + + return _compute_grade_involution(device=x.device, dtype=x.dtype) * x diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/nonlinearities.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3a4c43eae9ff40b7d1754f592220f9482e9a74 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/nonlinearities.py @@ -0,0 +1,111 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import math + +import torch + +_GATED_GELU_DIV_FACTOR = math.sqrt(2 / math.pi) * 2 + + +def gated_relu(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated ReLU nonlinearity. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + ReLU(gates) * x. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes ReLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.relu(gates) + outputs = weights * x + return outputs + + +def gated_sigmoid(x: torch.Tensor, gates: torch.Tensor): + """Pin-equivariant gated sigmoid nonlinearity. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + sigmoid(gates) * x. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes sigmoid(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.sigmoid(gates) + outputs = weights * x + return outputs + + +def gated_gelu(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated GeLU nonlinearity without division. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + GeLU(gates) * x. + + References + ---------- + Dan Hendrycks, Kevin Gimpel, "Gaussian Error Linear Units (GELUs)", arXiv:1606.08415 + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes GeLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.gelu(gates, approximate="tanh") + outputs = weights * x + return outputs + + +def gated_gelu_divide(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated GeLU nonlinearity with division. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + GeLU(gates) * x / gates. + + References + ---------- + Dan Hendrycks, Kevin Gimpel, "Gaussian Error Linear Units (GELUs)", arXiv:1606.08415 + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes GeLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.sigmoid(_GATED_GELU_DIV_FACTOR * (gates + 0.044715 * gates**3)) + outputs = weights * x + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/normalization.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..2da0b51e07850dd3a1313d5873665b321342a2e7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/primitives/normalization.py @@ -0,0 +1,49 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.primitives.invariants import inner_product + + +def equi_layer_norm( + x: torch.Tensor, channel_dim: int = -2, gain: float = 1.0, epsilon: float = 0.01 +) -> torch.Tensor: + """Equivariant LayerNorm for multivectors. + + Rescales input such that `mean_channels |inputs|^2 = 1`, where the norm is the GA norm and the + mean goes over the channel dimensions. + + Using a factor `gain > 1` makes up for the fact that the GP norm overestimates the actual + standard deviation of the input data. + + Parameters + ---------- + x : torch.Tensor with shape `(batch_dim, *channel_dims, 16)` + Input multivectors. + channel_dim : int + Channel dimension index. Defaults to the second-last entry (last are the multivector + components). + gain : float + Target output scale. + epsilon : float + Small numerical factor to avoid instabilities. By default, we use a reasonably large number + to balance issues that arise from some multivector components not contributing to the norm. + + Returns + ------- + outputs : torch.Tensor with shape `(batch_dim, *channel_dims, 16)` + Normalized inputs. + """ + + # Compute mean_channels |inputs|^2 + squared_norms = inner_product(x, x) + squared_norms = torch.mean(squared_norms, dim=channel_dim, keepdim=True) + + # Insure against low-norm tensors (which can arise even when `x.var(dim=-1)` is high b/c some + # entries don't contribute to the inner product / GP norm!) + squared_norms = torch.clamp(squared_norms, epsilon) + + # Rescale inputs + outputs = gain * x / torch.sqrt(squared_norms) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/__init__.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/clifford.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/clifford.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bf4792dee4d6bd12bf944ff1b45b48971402da --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/clifford.py @@ -0,0 +1,130 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Geometric algebra operations based on the clifford library.""" + +from typing import Optional + +import clifford +import numpy as np +import torch +from clifford import pga as PGA + + +def np_to_mv(array): + """Shorthand to transform a numpy array to a PGA multivector.""" + return clifford.MultiVector(PGA.layout, value=array) + + +def tensor_to_mv(tensor): + """Shorthand to transform a numpy array to a PGA multivector.""" + return np_to_mv(tensor.detach().cpu().numpy()) + + +def tensor_to_mv_list(tensor): + """Transforms a torch.Tensor to a list of multivector objects.""" + + tensor = tensor.reshape((-1, 16)) + mv_list = [tensor_to_mv(x) for x in tensor] + + return mv_list + + +def mv_list_to_tensor(multivectors, batch_shape=None): + """Transforms a list of multivector objects to a torch.Tensor.""" + + tensor = torch.from_numpy(np.array([mv.value for mv in multivectors])).to(torch.float32) + if batch_shape is not None: + tensor = tensor.reshape(*batch_shape, 16) + + return tensor + + +def sample_pin_multivector(spin: bool = False, rng: Optional[np.random.Generator] = None): + """Samples from the Pin(3,0,1) group as a product of reflections.""" + + if rng is None: + rng = np.random.default_rng() + + # Sample number of reflections we want to multiply + if spin: + i = np.random.randint(3) * 2 + else: + i = np.random.randint(5) + + # If no reflections, just return unit scalar + if i == 0: + return PGA.blades[""] + + multivector = 1.0 + for _ in range(i): + # Sample reflection vector + vector = np.zeros(16) + vector[1:5] = rng.normal(size=4) + vector_mv = np_to_mv(vector) + vector_mv = vector_mv / vector_mv.mag2() ** 0.5 + + # Multiply together (geometric product) + multivector = multivector * vector_mv + + return multivector + + +def get_parity(mv): + """Gets parity of a clifford multivector. + + Given a clifford multivector, returns True if it is pure-odd-grade, False if it is pure-even + grade, and raises a RuntimeError if it is mixed. + """ + if mv == mv.even: + return False + if mv == mv.odd: + return True + raise RuntimeError(f"Mixed-grade multivector: {mv}") + + +def sandwich(u, x): + """Given clifford multivectors, computes their sandwich product. + + Specifically, given a Pin element u and a PGA element x, both given as clifford multivectors, + computes the sandwich product + ``` + sandwich(x, u) = (-1)^(grade(u) * grade(x)) u x u^{-1} . + ``` + + If `u` is of odd grades, then this is equal to `u * grade_involute(x) * u^{-1}`. + If `u` is of even grades, then this is equal to `u * x * u^{-1}`. + """ + + if get_parity(u): + return u * x.gradeInvol() * u.shirokov_inverse() + + return u * x * u.shirokov_inverse() + + +class SlowRandomPinTransform: + """Random Pin transform on a multivector torch.Tensor. + + Slow, only used for testing purposes. Breaks computational graph. + """ + + def __init__(self, spin=False, rng=None): + super().__init__() + self._u = sample_pin_multivector(spin, rng) + self._u_inverse = self._u.shirokov_inverse() + + def __call__(self, inputs: torch.Tensor) -> torch.Tensor: + """Apply Pin transformation to multivector inputs.""" + # Input shape + assert inputs.shape[-1] == 16 + batch_dims = inputs.shape[:-1] + + # Convert inputs to list of multivectors + inputs_mv = tensor_to_mv_list(inputs) + + # Transform + outputs_mv = [sandwich(self._u, x) for x in inputs_mv] + + # Back to tensor + outputs = mv_list_to_tensor(outputs_mv, batch_shape=batch_dims) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/compile_linear.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/compile_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..3db8ac0f70b051cbaa87b47006abf6dd6f4e1748 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/compile_linear.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# Copyright (c) 2024 Qualcomm Technologies, Inc. +# All rights reserved. + +from typing import Optional, Tuple, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from gatr.layers.linear import EquiLinear +from gatr.primitives.linear import _compute_pin_equi_linear_basis + + +class CompiledLinear(nn.Module): + """A drop-in replacement for EquiLinear for fast inference. + + Not trainable. Parameters must be set by hand. + + Parameters + ---------- + in_mv_channels : int + Input multivector channels + out_mv_channels : int + Output multivector channels + bias : bool + Whether a bias term is added to the scalar component of the multivector outputs + in_s_channels : int or None + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + bias: bool = True, + ) -> None: + super().__init__() + in_channels = 16 * in_mv_channels + (in_s_channels or 0) + out_channels = 16 * out_mv_channels + (out_s_channels or 0) + self.register_buffer("weight", torch.zeros(out_channels, in_channels)) + self.register_buffer("bias", torch.zeros(out_channels) if bias else None) + self._out_mv_channels = out_mv_channels + self._out_s_channels = out_s_channels + + def forward( + self, multivectors: torch.Tensor, scalars: Optional[torch.Tensor] = None + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Compute compiled linear map. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + b = multivectors.shape[:-2] + inputs = multivectors.view(*b, -1) + if scalars is not None: + inputs = torch.cat([inputs, scalars], -1) + outputs = F.linear(inputs, self.weight, self.bias) # pylint: disable=not-callable + outputs_mv = outputs[..., : 16 * self._out_mv_channels].view(*b, -1, 16) + if self._out_s_channels is None: + outputs_s = None + else: + outputs_s = outputs[..., 16 * self._out_mv_channels :] + + return outputs_mv, outputs_s + + +def compile_equi_linear(equi_linear: EquiLinear) -> CompiledLinear: + """Transform EquiLinear module to equivalent CompiledLinear module. + + Used for fast inference, not trainable! + + Parameters + ---------- + equi_linear : EquiLinear + + Returns + ------- + CompiledLinear + """ + # Figure out hyperparameters of EquiLinear from parameter shapes + out_mv_channels, in_mv_channels, _ = equi_linear.weight.shape + in_s_channels = equi_linear.s2mvs.weight.shape[1] if equi_linear.s2mvs else None + out_s_channels = equi_linear.mvs2s.weight.shape[0] if equi_linear.mvs2s else None + if in_s_channels is None: + bias = equi_linear.bias is not None + else: + bias = equi_linear.s2mvs.bias is not None + + compiled = CompiledLinear( + in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias=bias + ) + compiled.to(device=equi_linear.weight.device, dtype=equi_linear.weight.dtype) + + # The number of channels the multivectors occupy + offset_in = in_mv_channels * 16 + offset_out = out_mv_channels * 16 + + # Materialize the equivariant maps by linearly combining the basis maps + basis = _compute_pin_equi_linear_basis( + device=equi_linear.weight.device, dtype=equi_linear.weight.dtype + ) + mv_mv_weight = torch.einsum("y x a, a i j -> y i x j", equi_linear.weight, basis) + compiled.weight[:offset_out, :offset_in] = mv_mv_weight.reshape(offset_out, offset_in) + + if in_s_channels: + compiled.weight[:offset_out:16, offset_in:] = equi_linear.s2mvs.weight + if out_s_channels: + compiled.weight[offset_out:, :offset_in:16] = equi_linear.mvs2s.weight + if in_s_channels and out_s_channels: + compiled.weight[offset_out:, offset_in:] = equi_linear.s2s.weight + + if bias: + if equi_linear.bias is not None: + compiled.bias[:offset_out:16] = equi_linear.bias.flatten() + elif equi_linear.s2mvs.bias is not None: + compiled.bias[:offset_out:16] = equi_linear.s2mvs.bias + if out_s_channels: + compiled.bias[offset_out:] = equi_linear.mvs2s.bias + + return compiled + + +def compile_equi_linear_submodules(model: nn.Module): + """Replace all EquiLinear submodules in module with compiled version. + + Parameters + ---------- + model : nn.Module + Model whose EquiLinear submodules will be replaced. Argument mutated! + """ + + def walker(module): + for name, submodule in module.named_children(): + if isinstance(submodule, EquiLinear): + compiled_linear = compile_equi_linear(submodule) + setattr(module, name, compiled_linear) + + model.apply(walker) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/dual_basis.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/dual_basis.py new file mode 100644 index 0000000000000000000000000000000000000000..e33f9a46398a780863b61d09c0dbb9a83ff29473 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/dual_basis.py @@ -0,0 +1,70 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import numpy as np +import torch +from clifford import pga as PGA +from clifford.pga import layout + +e1, e2, e3, e123 = PGA.blades["e1"], PGA.blades["e2"], PGA.blades["e3"], PGA.blades["e123"] + + +def point_r3_to_mv(v): + """Helper function to construct basis for reference_dual().""" + return e123 + sum(v * [e1.dual(), e2.dual(), e3.dual()]) + + +def point_r3_expand(p_r3): + """Helper function to construct basis for reference_dual().""" + p_sq = np.einsum("...i,...j->...ij", p_r3, p_r3).reshape(*p_r3.shape[:-1], 9) + p_exp = np.concatenate([p_sq, p_r3, np.ones((*p_r3.shape[:-1], 1))], -1) + return p_exp + + +def sw(u, x): + """Helper function to construct basis for reference_dual().""" + grades = set(g % 2 for g in u.grades()) + assert len(grades) == 1, f"{u} is mixed odd/even" + if grades.pop() == 0: + return u * x * u.shirokov_inverse() + return u * x.gradeInvol() * u.shirokov_inverse() + + +def dual(p, x): + """Helper function to construct basis for reference_dual().""" + p = p(3) # Take the trivector of p, making it a point + s = p | -e123 # The scale to make it a proper point + p = p / s # Normalize so that e123 dim is 1 + t = 0.5 - (e123 * p) / 2 # Translation from p to origin + assert sw(t, p) == e123 # Assert this works + x_t = sw(t, x) # Move x to origin + y = x_t.dual() # Dualize at origin + y_t = sw(t.inv(), y) # Move back to p + return y_t * s # Re-apply scale of p + + +def compute_dual_basis(): + """Helper function to construct basis for reference_dual().""" + num_points = 100 + p_r3 = np.random.rand(num_points, 3) + p_mv = [point_r3_to_mv(v) for v in p_r3] + p_exp = point_r3_expand(p_r3) + ws = [] + for i in range(16): + x = layout.MultiVector(np.eye(16)[i]) + ys = np.stack([dual(p, x).value for p in p_mv]) + w = (np.linalg.pinv(p_exp) @ ys).T + ws.append(w) + w = np.stack(ws, 1) + w_rounded = (w * 2).round() / 2 # Round to halves + np.testing.assert_allclose(w, w_rounded, atol=1e-10) + w = w_rounded + return w + + +@lru_cache(5) +def compute_dual_basis_torch(device): + """Helper function to construct basis for reference_dual().""" + w = compute_dual_basis() + return torch.tensor(w, dtype=torch.float32, device=device) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/einsum.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..63de78511d387c4c6651ecb23925796996917004 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/einsum.py @@ -0,0 +1,40 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""This module provides efficiency improvements over torch's einsum through caching.""" + +import functools +from typing import List, Sequence + +import opt_einsum +import torch + + +def custom_einsum(equation: str, *operands: torch.Tensor, path: List[int]) -> torch.Tensor: + """Computes einsum with a custom contraction order.""" + + # Justification: For the sake of performance, we need direct access to torch's private methods. + + # pylint:disable-next=protected-access + return torch._VF.einsum(equation, operands, path=path) # type: ignore[attr-defined] + + +def cached_einsum(equation: str, *operands: torch.Tensor) -> torch.Tensor: + """Computes einsum with a cached optimal contraction. + + Inspired by upstream + https://github.com/pytorch/pytorch/blob/v1.13.0/torch/functional.py#L381. + """ + op_shape = tuple(op.shape for op in operands) + path = _get_cached_path_for_equation_and_shapes(equation=equation, op_shape=op_shape) + + return custom_einsum(equation, *operands, path=path) + + +@functools.lru_cache(maxsize=None) +def _get_cached_path_for_equation_and_shapes( + equation: str, op_shape: Sequence[torch.Tensor] +) -> List[int]: + """Provides caching of optimal path.""" + tupled_path = opt_einsum.contract_path(equation, *op_shape, optimize="optimal", shapes=True)[0] + + return [item for pair in tupled_path for item in pair] diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/logger.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d7956515b74038f084796eaab69708cfae4951 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/logger.py @@ -0,0 +1,6 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import logging + +logger = logging.getLogger("gatr_experiment") +logging_initialized = False diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/misc.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..1f34aa24e38e52b83824a8bf7a9f539cc3fc96b5 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/misc.py @@ -0,0 +1,146 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from collections.abc import Mapping +from functools import lru_cache +from itertools import product + +import numpy as np +import torch + + +class NaNError(BaseException): + """Exception to be raise when the training encounters a NaN in loss or model weights.""" + + +def get_device() -> torch.device: + """Gets CUDA if available, CPU else.""" + return torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + + +def frequency_check(step, every_n_steps, skip_initial=False, include_fractional=None): + """Checks whether an action should be performed at a given step and frequency. + + If `include_fractional` is given, the check also returns True when + `step == round(every_n_steps * fraction)` for each `fraction` in `include_fractional`. + + Parameters + ---------- + step : int + Step number (one-indexed) + every_n_steps : None or int + Desired action frequency. None or 0 correspond to never executing the action. + skip_initial : bool + If True, frequency_check returns False at step 0. + include_fractional : None or tuple of float + If not None, the check also returns True when `step == round(every_n_steps * fraction)` + for each `fraction` in `include_fractional`. + + Returns + ------- + decision : bool + Whether the action should be executed. + """ + + if every_n_steps is None or every_n_steps == 0: + return False + + if skip_initial and step == 0: + return False + + if include_fractional is not None: + for fraction in include_fractional: + if step == int(round(fraction * every_n_steps)): + return True + + return step % every_n_steps == 0 + + +def flatten_dict(d, parent_key="", sep="."): + """Flattens a nested dictionary with str keys.""" + items = [] + for k, v in d.items(): + new_key = parent_key + sep + k if parent_key else k + if isinstance(v, Mapping): + items.extend(flatten_dict(v, new_key, sep=sep).items()) + else: + items.append((new_key, v)) + return dict(items) + + +def sample_uniform_in_circle(n, min_radius=0.0, max_radius=1.0): + """Samples uniformly in a 2D circle using batched rejection sampling.""" + + assert 0.0 <= min_radius < max_radius, "Inconsistent inputs to sample_uniform_in_circle" + + mask = None + samples = None + + while samples is None or np.sum(mask) > 0: + new_samples = max_radius * np.random.uniform(low=-1, high=1, size=(n, 2)) + + if samples is None: + samples = new_samples + else: + samples = (1 - mask) * samples + mask * new_samples + + r2 = np.sum(samples**2, axis=-1) + mask = np.logical_or((r2 < min_radius**2), (r2 > max_radius**2))[:, np.newaxis] + + return samples + + +def sample_log_uniform(min_, max_, size): + """Samples log-uniformly from (min_, max_).""" + if isinstance(size, tuple): + n = int(np.product(size)) + else: + n = size + + log_x = np.random.rand(n) * (np.log(max_) - np.log(min_)) + np.log(min_) + x = np.exp(log_x) + + if isinstance(size, tuple): + x = x.reshape(size) + + return x + + +@lru_cache() +@torch.no_grad() +def make_full_edge_index(num_nodes, batchsize=1, self_loops=False, device=torch.device("cpu")): + """Creates a PyG-style edge index for a fully connected graph of `num_nodes` nodes.""" + + # Construct fully connected edge index + src, dst = [], [] + for i, j in product(range(num_nodes), repeat=2): + if not self_loops and i == j: + continue + src.append(i) + dst.append(j) + + edge_index_per_batch = torch.LongTensor([src, dst]).to(device) + + # Repeat for each batch element + if batchsize > 1: + edge_index_list = [edge_index_per_batch + k * num_nodes for k in range(batchsize)] + edge_index = torch.cat(edge_index_list, dim=1) + else: + edge_index = edge_index_per_batch + + return edge_index + + +def get_batchsize(data): + """Given either a tensor or a list of tensors or a dict of tensors, returns the batchsize.""" + + if isinstance(data, Mapping): + assert len(data) > 0 + data = next(iter(data.values())) + elif isinstance(data, (tuple, list)): + assert len(data) > 0 + data = data[0] + elif isinstance(data, (tuple, list)): + assert len(data) > 0 + data = data[0] + + return len(data) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/mlflow.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2f5ff71c02d75c9b5244f3e3d66c4738d18607 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/mlflow.py @@ -0,0 +1,68 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import time +from typing import Optional, Union + +import mlflow +import numpy as np + +from gatr.utils.logger import logger + +MAX_LOG_ATTEMPTS = 20 +BASE_WAIT_TIME = 0.2 # Base wait time between attempts in seconds +WAIT_TIME_FACTOR = 1.5 # Increase of the wait time for each successive trial +WAIT_TIME_RANDOM = ( + 0.5 # Upper bound on random wait time that is added to break synchronicity of multiple jobs +) + +LOGGING_ENABLED = True + + +def log_mlflow( + key: str, value: Union[float, str], step: Optional[int] = None, kind: str = "metric" +) -> None: + """Logs metric or param to MLflow. + + Catches exceptions due to locked or unavailable DB and then retries. + + Parameters + ---------- + key : str + Key to log + value : float or str + Value to log + step : None or int + Step to log + kind : {"metric", "param"} + Whether to log a metric or a parameter + + Raises + ------ + ValueError + If `kind` is invalid + """ + if not LOGGING_ENABLED: + return + + for attempt in range(MAX_LOG_ATTEMPTS): + try: + if kind == "metric": + mlflow.log_metric(key, value, step=step) + elif kind == "param": + mlflow.log_param(key, value) + else: + raise ValueError( + f"Unknown MLflow logging kind {kind}, should be 'metric' or 'param'" + ) + return + except Exception: # pylint: disable=broad-except + wait_time = ( + BASE_WAIT_TIME * WAIT_TIME_FACTOR**attempt + WAIT_TIME_RANDOM * np.random.rand() + ) + logger.warning( + f"Exception when logging to MLflow at step {step} (attempt {attempt + 1}). " + f"Waiting for {wait_time:.1f}s before trying again." + ) + time.sleep(wait_time) + + logger.error(f"Warning: Failed to write to MLflow {MAX_LOG_ATTEMPTS} times") diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/plotting.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..85755260ccd3d7137c6cfe60fb7bac30f6dd9999 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/plotting.py @@ -0,0 +1,42 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Matplotlib plotting settings.""" + +FONTSIZE = 11 # pt +PAGEWIDTH = 11 # inches +MATPLOTLIB_PARAMS = { + # Font sizes + "font.size": FONTSIZE, # controls default text sizes + "axes.titlesize": FONTSIZE, # fontsize of the axes title + "axes.labelsize": FONTSIZE, # fontsize of the x and y labels + "xtick.labelsize": FONTSIZE, # fontsize of the tick labels + "ytick.labelsize": FONTSIZE, # fontsize of the tick labels + "legend.fontsize": FONTSIZE, # legend fontsize + "figure.titlesize": FONTSIZE, # fontsize of the figure title + # Figure size and DPI + "figure.dpi": 100, + "savefig.dpi": 300, + "figure.figsize": (PAGEWIDTH / 2, PAGEWIDTH / 2), + # colors + "lines.markeredgewidth": 0.8, + "axes.edgecolor": "black", + "axes.grid": False, + "grid.color": "0.9", + "axes.grid.which": "both", + # x-axis ticks and grid + "xtick.bottom": True, + "xtick.direction": "out", + "xtick.color": "black", + "xtick.major.bottom": True, + "xtick.major.size": 4, + "xtick.minor.bottom": True, + "xtick.minor.size": 2, + # y-axis ticks and grid + "ytick.left": True, + "ytick.direction": "out", + "ytick.color": "black", + "ytick.major.left": True, + "ytick.major.size": 4, + "ytick.minor.left": True, + "ytick.minor.size": 2, +} diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/quaternions.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/quaternions.py new file mode 100644 index 0000000000000000000000000000000000000000..f720a57afe81d286f9102a2e2fd287e0a0bfa400 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/quaternions.py @@ -0,0 +1,66 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/pimdh/lie-vae/blob/c473d91c494b9e80f6ac2998b1b6b927d09df259/lie_vae/lie_tools.py +by Luca Falorsi, Pim de Haan, Tim Davidson at https://github.com/pimdh/lie-vae + +MIT License + +Copyright (c) 2020 Pim de Haan, Luca Falorsi, Tim Davidson + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +import torch + + +def random_quaternion(batch_dims): + """Returns a unit quaternion, uniformly sampled from the 3-sphere.""" + q = torch.randn(*batch_dims, 4) + return q / torch.norm(q, dim=-1, keepdim=True) + + +def quaternion_to_rotation_matrix(q): + """Normalises q and maps to group matrix. + + Assumes [x y z w] quaternion format with ij=k (Hamilton) convention. + """ + q = q[..., [3, 0, 1, 2]] # Convert to [w x y z] order + + q = q / q.norm(p=2, dim=-1, keepdim=True) + r, i, j, k = q[..., 0], q[..., 1], q[..., 2], q[..., 3] + + mat = torch.stack( + [ + r * r + i * i - j * j - k * k, + 2 * (i * j - k * r), + 2 * (i * k + j * r), + 2 * (i * j + k * r), + r * r - i * i + j * j - k * k, + 2 * (j * k - i * r), + 2 * (i * k - j * r), + 2 * (j * k + i * r), + r * r - i * i - j * j + k * k, + ], + -1, + ) + + return mat.view(*q.shape[:-1], 3, 3) diff --git a/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/tensors.py b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..5bad296c6d07df48465d236df17a86e65e8ba3c7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/lib/gatr/utils/tensors.py @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Union + +import torch +from torch import Tensor + + +def expand_pairwise(*tensors, exclude_dims=()): + """Expand tensors to largest, optionally excluding some axes.""" + max_dim = max(t.dim() for t in tensors) + shapes = [(1,) * (max_dim - t.dim()) + t.shape for t in tensors] + max_shape = [max(s[d] for s in shapes) for d in range(max_dim)] + for d in exclude_dims: + max_shape[d] = -1 + return tuple(t.expand(tuple(max_shape)) for t in tensors) + + +def to_nd(tensor, d): + """Make tensor n-dimensional, group extra dimensions in first.""" + return tensor.view(-1, *(1,) * (max(0, d - 1 - tensor.dim())), *tensor.shape[-(d - 1) :]) + + +def assert_equal(vals): + """Assert all values in sequence are equal.""" + for v in vals: + assert v == vals[0] + + +def block_stack(tensors, dim1, dim2): + """Block diagonally stack tensors along dimensions dim1 and dim2.""" + assert_equal([t.dim() for t in tensors]) + shapes = [t.shape for t in tensors] + shapes_t = list(map(list, zip(*shapes))) + for i, ss in enumerate(shapes_t): + if i not in (dim1, dim2): + assert_equal(ss) + + dim2_len = sum(shapes_t[dim2]) + opts = dict(device=tensors[0].device, dtype=tensors[0].dtype) + + padded_tensors = [] + offset = 0 + for tensor in tensors: + before_shape = list(tensor.shape) + before_shape[dim2] = offset + after_shape = list(tensor.shape) + after_shape[dim2] = dim2_len - tensor.shape[dim2] - offset + before = torch.zeros(*before_shape, **opts) + after = torch.zeros(*after_shape, **opts) + padded = torch.cat([before, tensor, after], dim2) + padded_tensors.append(padded) + offset += tensor.shape[dim2] + return torch.cat(padded_tensors, dim1) + + +def construct_reference_multivector(reference: Union[Tensor, str], inputs: Tensor) -> Tensor: + """Constructs a reference vector for the equivariant join. + + Parameters + ---------- + reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + inputs : Tensor with shape (..., num_items_1, num_items_2, in_mv_channels, 16) + Input multivectors. + + Returns + ------- + reference_mv : Tensor with shape (..., 16) + Reference multivector for the equivariant join. + + Raises + ------ + ValueError + If `reference` is neither "data", "canonical", nor a Tensor. + """ + + if reference == "data": + # When using torch-geometric-style batching, this code should be adapted to perform the + # mean over the items in each batch, but not over the batch dimension. + # We leave this as an exercise for the practitioner :) + mean_dim = tuple(range(1, len(inputs.shape) - 1)) + reference_mv = torch.mean(inputs, dim=mean_dim, keepdim=True) # (batch, 1, ..., 1, 16) + elif reference == "canonical": + reference_mv = torch.zeros(16).to(inputs.device, inputs.dtype) + reference_mv[..., [14, 15]] = 1.0 + else: + if not isinstance(reference, Tensor): + raise ValueError( + 'Reference needs to be "data", "canonical", or torch.Tensor, but found {reference}' + ) + reference_mv = reference + + return reference_mv diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.10/artery_experiment.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/artery_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baf1cee8a27ef8459348b64c43e6b8219b66be --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/artery_experiment.py @@ -0,0 +1,18 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.arteries.experiment import ArteryExperiment + + +@hydra.main(config_path="../config", config_name="arteries", version_base=None) +def main(cfg): + """Entry point for artery experiment.""" + exp = ArteryExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.10/generate_nbody_dataset.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/generate_nbody_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4c812b488ab49c8f5d1ea80c2376f56595feb09b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/generate_nbody_dataset.py @@ -0,0 +1,59 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +from pathlib import Path + +import hydra +import numpy as np + +from gatr.experiments.nbody import NBodySimulator + + +def generate_dataset(filename, simulator, num_samples, num_planets=5, domain_shift=False): + """Samples from n-body simulator and stores the results at `filename`.""" + assert not Path(filename).exists() + m, x_initial, v_initial, x_final, trajectories = simulator.sample( + num_samples, num_planets=num_planets, domain_shift=domain_shift + ) + np.savez( + filename, + m=m, + x_initial=x_initial, + v_initial=v_initial, + x_final=x_final, + trajectories=trajectories, + ) + + +def generate_datasets(path): + """Generates a canonical set of datasets for the n-body problem, stores them in `path`.""" + path = Path(path).resolve() + path.mkdir(parents=True, exist_ok=True) + + print(f"Creating gravity dataset in {str(path)}") + + simulator = NBodySimulator() + generate_dataset(path / "train.npz", simulator, 100000, num_planets=3, domain_shift=False) + generate_dataset(path / "val.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset(path / "eval.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset( + path / "e3_generalization.npz", simulator, 5000, num_planets=3, domain_shift=True + ) + generate_dataset( + path / "object_generalization.npz", simulator, 5000, num_planets=5, domain_shift=False + ) + + print("Done, have a nice day!") + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body dataset generation.""" + data_dir = cfg.data.data_dir + np.random.seed(cfg.seed) + generate_datasets(data_dir) + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.10/nbody_experiment.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/nbody_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..89568f7b0020245b23a7ec451cd2c23b583e6107 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.10/nbody_experiment.py @@ -0,0 +1,18 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.nbody import NBodyExperiment + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body experiment.""" + exp = NBodyExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.11/artery_experiment.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/artery_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..f4baf1cee8a27ef8459348b64c43e6b8219b66be --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/artery_experiment.py @@ -0,0 +1,18 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.arteries.experiment import ArteryExperiment + + +@hydra.main(config_path="../config", config_name="arteries", version_base=None) +def main(cfg): + """Entry point for artery experiment.""" + exp = ArteryExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.11/generate_nbody_dataset.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/generate_nbody_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4c812b488ab49c8f5d1ea80c2376f56595feb09b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/generate_nbody_dataset.py @@ -0,0 +1,59 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +from pathlib import Path + +import hydra +import numpy as np + +from gatr.experiments.nbody import NBodySimulator + + +def generate_dataset(filename, simulator, num_samples, num_planets=5, domain_shift=False): + """Samples from n-body simulator and stores the results at `filename`.""" + assert not Path(filename).exists() + m, x_initial, v_initial, x_final, trajectories = simulator.sample( + num_samples, num_planets=num_planets, domain_shift=domain_shift + ) + np.savez( + filename, + m=m, + x_initial=x_initial, + v_initial=v_initial, + x_final=x_final, + trajectories=trajectories, + ) + + +def generate_datasets(path): + """Generates a canonical set of datasets for the n-body problem, stores them in `path`.""" + path = Path(path).resolve() + path.mkdir(parents=True, exist_ok=True) + + print(f"Creating gravity dataset in {str(path)}") + + simulator = NBodySimulator() + generate_dataset(path / "train.npz", simulator, 100000, num_planets=3, domain_shift=False) + generate_dataset(path / "val.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset(path / "eval.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset( + path / "e3_generalization.npz", simulator, 5000, num_planets=3, domain_shift=True + ) + generate_dataset( + path / "object_generalization.npz", simulator, 5000, num_planets=5, domain_shift=False + ) + + print("Done, have a nice day!") + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body dataset generation.""" + data_dir = cfg.data.data_dir + np.random.seed(cfg.seed) + generate_datasets(data_dir) + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/build/scripts-3.11/nbody_experiment.py b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/nbody_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..89568f7b0020245b23a7ec451cd2c23b583e6107 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/build/scripts-3.11/nbody_experiment.py @@ -0,0 +1,18 @@ +#!python +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.nbody import NBodyExperiment + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body experiment.""" + exp = NBodyExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/config/arteries.yaml b/gafl/build/geometric-algebra-transformer/config/arteries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d893e628e4d4adf2b434203d0875648b9645600a --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/arteries.yaml @@ -0,0 +1,66 @@ +exp_name: arteries +run_name: default + +base_dir : ??? +exp_dir: '${base_dir}/experiments/${exp_name}/${run_name}' + +seed: ??? +debug: false + +checkpoint: null + +data: + data_dir: '${base_dir}/data/arteries' + subsample: null + + mv_channels_in: 3 + mv_channels_out: 1 + scalar_channels_in: 1 + scalar_channels_out: 1 + baseline_channels_in: 7 + baseline_channels_out: 3 + + rotate_train: true + rotate_test: true + +training: + output_regularization: 0 + + steps: 200000 + batchsize: 8 + eval_batchsize: 1 + + lr: 3e-4 + lr_decay: 0.01 + clip_grad_norm: 10.0 + weight_decay: 0.0 + + early_stopping: true + + float16: false + ema: false + + log_every_n_steps: 100 + validate_every_n_steps: 1000 + plot_every_n_steps: 10000 + save_model_every_n_steps: 1000 + update_lr_every_n_steps: 1000 + + eval_device: cuda + progressbar: true + detect_anomaly: false + + # Following config is unused for batch size>1, as we use xformers here + force_xformers: false + enable_flash_sdp: false + enable_math_sdp: true + enable_mem_efficient_sdp: false + +mlflow: + db: '${base_dir}/tracking/mlflow.db' + artifacts: '${base_dir}/tracking/artifacts' + +defaults: + - model: gatr_arteries + - hydra + - _self_ # Ensures that entries in this file overwrite everything references above, even in hydra <= 1.0 diff --git a/gafl/build/geometric-algebra-transformer/config/hydra.yaml b/gafl/build/geometric-algebra-transformer/config/hydra.yaml new file mode 100644 index 0000000000000000000000000000000000000000..63a28d91ca7f06178e4ad765cd0ed9cc970269be --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/hydra.yaml @@ -0,0 +1,14 @@ +# The settings below keep hydra from creating new directories, changing the working directory, or hijacking the configuration of the logger +# See https://stackoverflow.com/questions/65104134/disable-file-output-of-hydra and https://github.com/facebookresearch/hydra/pull/1130 +hydra: + output_subdir: null + run: + dir: . + hydra_logging: + version: 1 + root: null + disable_existing_loggers: false + job_logging: + version: 1 + root: null + disable_existing_loggers: false diff --git a/gafl/build/geometric-algebra-transformer/config/model/gatr_arteries.yaml b/gafl/build/geometric-algebra-transformer/config/model/gatr_arteries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b309eca0f0b102ab680ab3d34f9046aa0dfd42f2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/gatr_arteries.yaml @@ -0,0 +1,26 @@ +_target_: gatr.experiments.arteries.wrappers.ArteryGATrWrapper + +net: + _target_: gatr.nets.GATr + + in_mv_channels: '${data.mv_channels_in}' + out_mv_channels: '${data.mv_channels_out}' + hidden_mv_channels: 8 + + in_s_channels: '${data.scalar_channels_in}' + out_s_channels: '${data.scalar_channels_out}' + hidden_s_channels: 32 + + num_blocks: 10 + reinsert_mv_channels: [0] + reinsert_s_channels: null + dropout_prob: null + + checkpoint_blocks: true + + attention: + num_heads: 4 + +defaults: + - /base_attention@net.attention + - /base_mlp@net.mlp \ No newline at end of file diff --git a/gafl/build/geometric-algebra-transformer/config/model/gatr_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/gatr_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d63ea0d4ae9beddfd9c516ddaf8f7c2face7bf48 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/gatr_nbody.yaml @@ -0,0 +1,22 @@ +_target_: gatr.experiments.nbody.wrappers.NBodyGATrWrapper + +net: + _target_: gatr.nets.GATr + + in_mv_channels: '${data.mv_channels_in}' + out_mv_channels: '${data.mv_channels_out}' + hidden_mv_channels: 16 + + in_s_channels: '${data.scalar_channels_in}' + out_s_channels: '${data.scalar_channels_out}' + hidden_s_channels: 128 + + num_blocks: 10 + checkpoint_blocks: false + reinsert_mv_channels: null + reinsert_s_channels: null + dropout_prob: null + +defaults: + - /base_attention@net.attention + - /base_mlp@net.mlp \ No newline at end of file diff --git a/gafl/build/geometric-algebra-transformer/config/model/gcagnn_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/gcagnn_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a278c5aafbd3a3f2c4ea7f244a12f2da975a0bf --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/gcagnn_nbody.yaml @@ -0,0 +1,18 @@ +_target_: gatr.experiments.nbody.wrappers.NBodyGCANWrapper + +geometric_batching: true + +net: + _target_: gatr.baselines.gcan.GCAGNN + + in_channels: ${data.mv_channels_in} + out_channels: ${data.mv_channels_out} + node_channels: 64 + message_channels: 64 + + mlp_hidden_channels: 128 + mlp_hidden_layers: 1 + + message_passing_steps: 4 + # From GCAN paper: + # "The GCA-GNN equals the parameters of the small [baseline GNN], using four hidden layers of 64 hidden features." diff --git a/gafl/build/geometric-algebra-transformer/config/model/gcamlp_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/gcamlp_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2283fa279b614c8390a9c3bb7528a9203bec893f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/gcamlp_nbody.yaml @@ -0,0 +1,17 @@ +_target_: gatr.experiments.nbody.wrappers.NBodyGCANWrapper + +geometric_batching: true + +net: + _target_: gatr.baselines.gcan.GCAMLP + + in_shape: + - 4 + - ${data.mv_channels_in} + out_shape: + - 4 + - ${data.mv_channels_out} + + # Settings from GCAN paper, Tetris experiment: + hidden_channels: 128 + hidden_layers: 2 diff --git a/gafl/build/geometric-algebra-transformer/config/model/mlp_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/mlp_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d873dce29c216d2dc685400900573f25567e6ace --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/mlp_nbody.yaml @@ -0,0 +1,14 @@ +_target_: gatr.experiments.nbody.wrappers.NBodyBaselineWrapper + +net: + _target_: gatr.baselines.mlp.MLP + + in_shape: + - 4 + - ${data.baseline_channels_in} + out_shape: + - 4 + - ${data.baseline_channels_out} + + hidden_channels: 384 + hidden_layers: 2 diff --git a/gafl/build/geometric-algebra-transformer/config/model/se3transformer_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/se3transformer_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07841d6b15e38e87bad3e32a89705a935572f20e --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/se3transformer_nbody.yaml @@ -0,0 +1,17 @@ +_target_: gatr.experiments.nbody.wrappers.NBodySE3TransformerWrapper + +canonicalize_to_com: true +canonicalize_mode: com + +net: + _target_: se3_transformer.experiments.nbody.nbody_models.SE3Transformer + + # Settings taken from n-body example in official repo + num_layers: 4 + num_channels: 8 + num_degrees: 4 + div: 4 + n_heads: 1 + si_m: "1x1" + si_e: "att" + x_ij: "add" diff --git a/gafl/build/geometric-algebra-transformer/config/model/segnn_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/segnn_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..02e4233cc8cb8fdd31945589518bda2bab7076ef --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/segnn_nbody.yaml @@ -0,0 +1,23 @@ +_target_: gatr.experiments.nbody.wrappers.NBodySEGNNWrapper + +neighbors: 3 +canonicalize_mode: even +lmax_attr: '${model.net.lmax_attr}' + +net: + _target_: gatr.baselines.segnn.SEGNNModel + + input_vec_channels: '${data.geobaseline_vec_channels_in}' + output_vec_channels: '${data.geobaseline_vec_channels_out}' + input_s_channels: '${data.geobaseline_s_channels_in}' + output_s_channels: '${data.geobaseline_s_channels_out}' + additional_message_s_channels: 2 + + hidden_features: 64 + lmax_h: 1 + lmax_attr: 1 + subspace_type: weightbalanced + layers: 4 + norm: none + pool: avg + task: node diff --git a/gafl/build/geometric-algebra-transformer/config/model/transformer_arteries.yaml b/gafl/build/geometric-algebra-transformer/config/model/transformer_arteries.yaml new file mode 100644 index 0000000000000000000000000000000000000000..965b8846cde3d47b99ad7a44842085b89ee2765f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/transformer_arteries.yaml @@ -0,0 +1,15 @@ +_target_: gatr.experiments.arteries.wrappers.ArteryBaselineWrapper + +net: + _target_: gatr.baselines.BaselineTransformer + + in_channels: '${data.baseline_channels_in}' + out_channels: '${data.baseline_channels_out}' + hidden_channels: 160 + + num_blocks: 10 + num_heads: 4 + multi_query: true + + pos_encoding: false + checkpoint_blocks: true \ No newline at end of file diff --git a/gafl/build/geometric-algebra-transformer/config/model/transformer_nbody.yaml b/gafl/build/geometric-algebra-transformer/config/model/transformer_nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9f1180f36ae3ce6d9c1f78bb841659c6d451b7f0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/model/transformer_nbody.yaml @@ -0,0 +1,13 @@ +_target_: gatr.experiments.nbody.wrappers.NBodyBaselineWrapper + +net: + _target_: gatr.baselines.BaselineTransformer + + in_channels: '${data.baseline_channels_in}' + out_channels: '${data.baseline_channels_out}' + hidden_channels: 384 + + num_blocks: 10 + num_heads: 8 + + pos_encoding: false diff --git a/gafl/build/geometric-algebra-transformer/config/nbody.yaml b/gafl/build/geometric-algebra-transformer/config/nbody.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca82c0df48b2f6c9115b02a62e7827d5cd79df85 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/config/nbody.yaml @@ -0,0 +1,66 @@ +exp_name: nbody +run_name: ??? + +base_dir : ??? +exp_dir: '${base_dir}/experiments/${exp_name}/${run_name}' + +seed: ??? +debug: false + +checkpoint: null + +data: + data_dir: '${base_dir}/data/nbody' + subsample: null + + mv_channels_in: 1 + mv_channels_out: 1 + scalar_channels_in: 1 + scalar_channels_out: 1 + baseline_channels_in: 7 + baseline_channels_out: 3 + geobaseline_vec_channels_in: 2 + geobaseline_vec_channels_out: 1 + geobaseline_s_channels_in: 1 + geobaseline_s_channels_out: 0 + +training: + output_regularization: 0.01 + + steps: 50000 + batchsize: 64 + eval_batchsize: 64 + + lr: 3e-4 + lr_decay: 0.01 + clip_grad_norm: 10.0 + weight_decay: 0.0 + + early_stopping: true + + float16: false + ema: false + + log_every_n_steps: 100 + validate_every_n_steps: 1000 + plot_every_n_steps: 1000 + save_model_every_n_steps: 0 + update_lr_every_n_steps: 1000 + + eval_device: cuda + progressbar: true + detect_anomaly: false + + force_xformers: false + enable_flash_sdp: false + enable_math_sdp: true + enable_mem_efficient_sdp: false + +mlflow: + db: '${base_dir}/tracking/mlflow.db' + artifacts: '${base_dir}/tracking/artifacts' + +defaults: + - model: gatr_nbody + - hydra + - _self_ # Ensures that entries in this file overwrite everything references above, even in hydra <= 1.0 diff --git a/gafl/build/geometric-algebra-transformer/docker/Dockerfile b/gafl/build/geometric-algebra-transformer/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0b1a6baa53218568dc9de968026f045408564d0e --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/docker/Dockerfile @@ -0,0 +1,25 @@ +FROM nvidia/cuda:11.7.1-base-ubuntu20.04 + +RUN apt update && \ + DEBIAN_FRONTEND=noninteractive apt install --yes --no-install-recommends \ + build-essential \ + cmake \ + ffmpeg \ + git \ + python-is-python3 \ + python3-dev \ + python3-pip \ + && \ + rm -rf /var/lib/apt/lists/* + +COPY docker/requirements.txt requirements.txt + +RUN python3 -m pip install --no-cache-dir --upgrade pip && \ + python3 -m pip install --no-cache-dir --upgrade --requirement requirements.txt +RUN python3 -m pip install --no-cache-dir pyg_lib torch_scatter torch_sparse torch_cluster torch_spline_conv -f https://data.pyg.org/whl/torch-2.0.0+cu117.html + +COPY docker/ext_packages /docker/ext_packages +RUN python3 /docker/ext_packages/install_upstream_python_packages.py + +COPY . /gatr/ +RUN python3 -m pip install --no-cache-dir /gatr && rm -rf /gatr diff --git a/gafl/build/geometric-algebra-transformer/docker/ext_packages/coronary-mesh-convolution_vtk-patch.patch b/gafl/build/geometric-algebra-transformer/docker/ext_packages/coronary-mesh-convolution_vtk-patch.patch new file mode 100644 index 0000000000000000000000000000000000000000..5bdcca172e13d2e3211f978de25c4deba2951db8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/docker/ext_packages/coronary-mesh-convolution_vtk-patch.patch @@ -0,0 +1,87 @@ +diff --git a/transforms/flow_extensions.py b/transforms/flow_extensions.py +index d0bfaeb..b8e5203 100644 +--- a/transforms/flow_extensions.py ++++ b/transforms/flow_extensions.py +@@ -1,4 +1,4 @@ +-from utils.artery_tools import IndexFinder, remove_vertices ++from utils.artery_tools import remove_vertices + import torch + import trimesh + import numpy as np +@@ -14,25 +14,18 @@ class RemoveFlowExtensions(object): + def __init__(self, factor=(5., 0)): + self.factor = factor + +- self.inlet = IndexFinder(pytorch=True) +- + def inlet_area(self, data): +- if hasattr(data, 'inlet_index'): +- +- # Inlet vertex mask +- vertex_mask = torch.full((data.num_nodes,), False) +- vertex_mask[data['inlet_index'].long()] = True +- +- # Determine the inlet mesh +- inlet = remove_vertices(data.clone(), vertex_mask) ++ assert hasattr(data, 'inlet_index') + +- # Use trimesh object for area computation +- area = trimesh.Trimesh(vertices=inlet.pos.numpy(), faces=inlet.face.t().numpy()).area ++ # Inlet vertex mask ++ vertex_mask = torch.full((data.num_nodes,), False) ++ vertex_mask[data['inlet_index'].long()] = True + +- else: ++ # Determine the inlet mesh ++ inlet = remove_vertices(data.clone(), vertex_mask) + +- # Read inlet mesh from boundary-condition file +- area = self.inlet.area(data.dir) ++ # Use trimesh object for area computation ++ area = trimesh.Trimesh(vertices=inlet.pos.numpy(), faces=inlet.face.t().numpy()).area + + return area + +diff --git a/transforms/geodesics.py b/transforms/geodesics.py +index fd35f12..b0e2a0e 100644 +--- a/transforms/geodesics.py ++++ b/transforms/geodesics.py +@@ -1,4 +1,3 @@ +-from utils.artery_tools import IndexFinder + import potpourri3d as pp3d + import torch + +@@ -10,18 +9,14 @@ class InletGeodesics(object): + - + """ + +- def __init__(self): +- self.inlet_indices = IndexFinder() +- + def __call__(self, data): + solver = pp3d.MeshHeatMethodDistanceSolver(data.pos.numpy(), data.face.t().numpy()) + + # Compute the minimum geodesic distances to the inlet +- if hasattr(data, 'inlet_index'): +- inlet = data['inlet_index'].numpy() ++ assert hasattr(data, "inlet_index") ++ ++ inlet = data['inlet_index'].numpy() + +- else: +- inlet, _ = self.inlet_indices(data.dir) + + geodesics = solver.compute_distance_multisource(inlet) + +diff --git a/utils/artery_tools.py b/utils/artery_tools.py +index e590eb6..64db3c7 100644 +--- a/utils/artery_tools.py ++++ b/utils/artery_tools.py +@@ -1,6 +1,4 @@ +-import vtk +-from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk +-import utils.vtk_tools ++import utils + import numpy as np + import torch + import trimesh diff --git a/gafl/build/geometric-algebra-transformer/docker/ext_packages/install_upstream_python_packages.py b/gafl/build/geometric-algebra-transformer/docker/ext_packages/install_upstream_python_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..a79c83a754296afc02b5f83e2fbbaa729f2c83ae --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/docker/ext_packages/install_upstream_python_packages.py @@ -0,0 +1,295 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Installs upstream Python packages which are not easily installable via pip. + +After a vanilla checkout, the structure of those repositories is roughly as follows: + +```text +repository-root/ +├── experiments +├── models +├── ... more folders and files ... +└── setup.py +``` + +We modify those repositories to look as follows: + +```text +repository-root/ +├── pyproject.toml +└── src + └── project-name + ├── experiments + ├── models + └── ... more folders and files, possibly some omitted ... +``` +where `setup.py` was deleted and a minimalist `pyproject.toml` was added. + +After this modification, they are pip-installable, and importable from `project-name`. + +To prevent large Docker images and multiple dependency resolution steps, the requirements of those +repositories were directly added to `docker/requirements.txt`. +""" + +import contextlib +import logging +import os +import shutil +import subprocess +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any, List, Optional + +from rope.base.project import Project +from rope.refactor import move + +logging.basicConfig(level=logging.DEBUG) + +SCRIPT_FOLDER = Path(__file__).resolve().parent +SRC_FOLDER = "src" +INIT_PY = "__init__.py" +SEGNN_RELEVANT_FOLDER = "models" + + +class PythonPackage: + """Functionality related to installing the Python code given as a repo.""" + + def __init__( + self, + name: str, + clone_url: str, + checksum_sha: str, + checkout_base_dir: Path, + patch_file: Optional[Path] = None, + ordered_refactoring: Optional[List[str]] = None, + ) -> None: + self._name = name + self._clone_url = clone_url + self._checksum_sha = checksum_sha + self._base_dir = checkout_base_dir + self._patch_file = patch_file + self._ordered_refactoring = ordered_refactoring + + self._logger = logging.getLogger(self._name) + + def install_package(self) -> None: + """Performs all steps necessary up to and including installation of the package.""" + self.clone_from_upstream() + self.checkout_commit() + self.apply_patches() + + self.remove_packaging_files() + self.add_new_pyproject_file() + + self.add_init_files() + self.move_to_project_folder() + self.move_to_src_folder() + + self.pip_install_refactored_package() + self._logger.info("Installation complete.") + + def _get_checkout_path(self) -> Path: + return self._base_dir / self._name + + def _get_refactored_path(self) -> Path: + return self._get_checkout_path() / SRC_FOLDER / self._name + + def clone_from_upstream(self) -> None: + """Clones the git repository from the clone URL provided upon instantiation.""" + self._logger.info(f"Cloning git repo at {self._clone_url}") + run_successfully(cmd=["git", "clone", self._clone_url, str(self._get_checkout_path())]) + + def checkout_commit(self) -> None: + """Checks out the commit hash provided upon instantiation.""" + cmd = ["git", "checkout", self._checksum_sha] + run_successfully(cmd, cwd=self._get_checkout_path()) + + def apply_patches(self) -> None: + """Applies patch from a patch file, if provided upon instantiation.""" + if self._patch_file is not None: + run_successfully(["git", "apply", str(self._patch_file)], cwd=self._get_checkout_path()) + + def add_init_files(self) -> None: + """Adds an `__init__.py` file for ever subfolder of checkout path (if missing).""" + for folder, _, _ in os.walk(self._get_checkout_path()): + folder_path = Path(folder) + if ".git" in folder_path.parts: + continue + init_file = folder_path / INIT_PY + if not init_file.exists(): + init_file.touch() + + def remove_packaging_files(self) -> None: + """Removes all packaging files.""" + for filename in ["setup.py", "setup.cfg", "pyproject.toml"]: + file = self._get_checkout_path() / filename + file.unlink(missing_ok=True) + + def add_new_pyproject_file(self) -> None: + """Adds a generic `pyproject.toml` file to the project root.""" + file = self._get_checkout_path() / "pyproject.toml" + file.write_text(f'[project]\nname = "{self._name}"\nversion = "1.0.0"') + + def move_to_project_folder(self) -> None: + """Moves Python files and folders into folder with the project's name, adapts imports.""" + # Creates folder ` / project-name / project-name` + self._logger.info("Moving Python files and folders to project subfolder.") + project_subfolder = self._get_checkout_path() / self._name + project_subfolder.mkdir() + self._move_files(project_subfolder=project_subfolder) + + def _move_files(self, project_subfolder: Path) -> None: + """Use rope to move files.""" + + # Move all files / dirs using rope - this takes care of refactoring the imports, too. + file_objs = list(self._get_checkout_path().iterdir()) + files = self._sort_files_by_priority([file for file in file_objs if file.is_file()]) + dirs = [file for file in file_objs if file.is_dir()] + rope_project = Project(str(self._get_checkout_path())) + rope_target = rope_project.get_resource(self._name) + for file_obj in files + dirs: + if not self.should_refactor(file_obj, target_path=project_subfolder): + continue + rel_pkg_path = file_obj.relative_to(self._get_checkout_path()) + rope_source = rope_project.get_resource(str(rel_pkg_path)) + mover = move.create_move(rope_project, rope_source) + changes = mover.get_changes(rope_target) + rope_project.do(changes) + # The `__init__.py` in the base folder was not yet moved. + init_py_src = self._get_checkout_path() / INIT_PY + init_py_target = self._get_checkout_path() / self._name / INIT_PY + init_py_src.rename(init_py_target) + + def _sort_files_by_priority(self, files: List[Path]) -> List[Path]: + """Sorts files for priority refactoring. + + This is necessary as else rope will get this wrong in some cases: + It can, for example, make a difference if we first refactor `module1.py` and then + `module2.py`, or the other way around. + """ + if self._ordered_refactoring is None: + return files + files_without_priority = [x for x in files if x.name not in self._ordered_refactoring] + base = self._get_checkout_path() + files_with_priority = [base / file for file in self._ordered_refactoring] + if not set(files_with_priority + files_without_priority) == set(files): + raise RuntimeError("Could not reproduce the full list of files to refactor, aborting.") + return files_with_priority + files_without_priority + + def move_to_src_folder(self) -> None: + """Moves package code to `src` folder. + + That is, we move the code from ` / project-name / project-name` + to ` / project-name / src / project-name`. + This allows easy installation with pip. + """ + + src_folder = self._get_checkout_path() / SRC_FOLDER + src_folder.mkdir() + shutil.move(str(self._get_checkout_path() / self._name), src_folder) + + def pip_install_refactored_package(self) -> None: + """Installs the refactored package using `pip`.""" + self._logger.info("pip-installing refactored package.") + run_successfully(["pip", "install", str(self._get_checkout_path())]) + + @staticmethod + def should_refactor(file_obj: Path, target_path: Path) -> bool: + """Decides whether a file object should be refactored or not.""" + refactor = True + if file_obj.name.startswith("."): + refactor = False + if not file_obj.is_dir(): + if not file_obj.suffix == ".py" or file_obj.name == "__init__.py": + refactor = False + # Do not move project folder into itself + if file_obj.name == target_path.name: + refactor = False + return refactor + + +class SegnnPackage(PythonPackage): + """Special installation for the segnn package required. + + The reason is that rope fails to move all files (utils.py). + As we are only interested in the models/* files, we restrict to those. + """ + + def _move_files(self, project_subfolder: Path) -> None: + """Move python files directly.""" + for file_obj in (self._get_checkout_path() / SEGNN_RELEVANT_FOLDER).iterdir(): + shutil.move(str(file_obj), str(project_subfolder)) + + +def install_packages() -> None: + """Refactors flat Python projects into installable form.""" + with TemporaryDirectory() as tmp_dir: + tmp_path = Path(tmp_dir) + for package in get_packages(tmp_path=tmp_path): + package.install_package() + + +def get_packages(tmp_path: Path) -> List[PythonPackage]: + """Gets list of all Python packages to install.""" + packages = [ + SegnnPackage( + name="segnn", + clone_url="https://github.com/RobDHess/Steerable-E3-GNN.git", + checksum_sha="1b95898f6f18204b510ae127d7f38cd29f610f4d", + checkout_base_dir=tmp_path, + ), + PythonPackage( + name="se3_transformer", + clone_url="https://github.com/FabianFuchsML/se3-transformer-public.git", + checksum_sha="3ab53da4a501d4aedf128453b91290a4a5d65a45", + checkout_base_dir=tmp_path, + ), + PythonPackage( + name="coronary_mesh_convolution", + clone_url="https://github.com/sukjulian/coronary-mesh-convolution", + checksum_sha="e6234e108b4d4399d8fe948f6f7fbf36e66638fe", + checkout_base_dir=tmp_path, + # Prevents installation of vtk + patch_file=SCRIPT_FOLDER / "coronary-mesh-convolution_vtk-patch.patch", + ordered_refactoring=["datasets.py", "data.py"], + ), + ] + return packages + + +def run_successfully(cmd: List[str], **kwargs: Any) -> None: + """Executes command in a subprocess, and in case of errors, prints stdout/stderr and fails.""" + proc = subprocess.run( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", check=False, **kwargs + ) + if proc.returncode != 0: + print("stdout:", proc.stdout, "stderr:", proc.stderr, sep="\n") + proc.check_returncode() + + +def verify_installation_through_imports() -> None: + """Tests if installation was successful by importing the installed modules.""" + + # pylint:disable=import-error,import-outside-toplevel,unused-import + logger = logging.getLogger("pip installation") + logger.info("Now running some imports to test installation...") + + # Mute output from imports to avoid distracting information. + with contextlib.redirect_stdout(None), contextlib.redirect_stderr(None): + from coronary_mesh_convolution import datasets # type: ignore[import] + from coronary_mesh_convolution.data import MultiscaleData # type: ignore[import] + from se3_transformer.equivariant_attention.fibers import Fiber # type: ignore[import] + from se3_transformer.equivariant_attention.from_se3cnn.SO3 import ( + irr_repr, # type: ignore[import] + ) + from se3_transformer.equivariant_attention.modules import GSE3Res # type: ignore[import] + from se3_transformer.utils import utils_profiling # type: ignore[import] + from segnn.balanced_irreps import BalancedIrreps # type: ignore[import] + from segnn.segnn.segnn import SEGNN # type: ignore[import] + + logger.info("Imports successful!") + + +if __name__ == "__main__": + install_packages() + verify_installation_through_imports() diff --git a/gafl/build/geometric-algebra-transformer/docker/requirements.txt b/gafl/build/geometric-algebra-transformer/docker/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..752dd2ca9ebf9a912711ed0fcb06dcf45bf0bbb4 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/docker/requirements.txt @@ -0,0 +1,90 @@ +## Code quality +black~=22.8.0 +isort~=5.13.2 +mypy==1.1.1 +pydocstyle +pylint~=2.15.0 +pytest-cov==3.0.0 +pytest==7.0.1 +xenon==0.9.0 + +## Types +types-tqdm + +## CLI +click==8.0.4 + +## Package mgmt +rope + +## Standard science stack +h5py +matplotlib +numpy==1.23 +pandas<2.0.0 +scipy +seaborn + +## Standard utils +celluloid +jupyter>=1.0.0 +jupyterlab +jupytext +rich +tqdm + +## Deep learning +einops +git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10 # Un-released latest master (pinned for repro); the latest released version 3.3.0 has bugs in shape-based contraction path computations (used for einsum) +torch-ema +torch==2.0.1 +torchvision + +## Experiment management +hydra-core +mlflow==2.4.1 ## Need to pin version to avoid database version issues +optuna +SQLAlchemy==1.4.46 ## Pandas 1.* doesn't work with SQLAlchemy 2.*, see https://stackoverflow.com/questions/75315117/attributeerror-connection-object-has-no-attribute-connect-when-use-df-to-sq +wandb + +## Project-specific: general +clifford==1.4.0 +xformers==0.0.20 + +## Project-specific: baselines +git+https://github.com/microsoft/cliffordlayers.git@74799cf4588a065916305bfcf2f030d84918f0ad # The current version on pip (0.1.1) doesn't have GCAN yet + +# segnn +e3nn>=0.4.1 +torch_geometric>=2.0.9 + +# se3-transformer +absl-py +certifi +chardet +cycler +Cython +dgl-cu110 +git+https://github.com/AMLab-Amsterdam/lie_learn.git +grpcio +idna +joblib +kiwisolver +Markdown +packaging +protobuf +pyparsing +python-dateutil +requests +scikit-learn +six +tensorboard +urllib3 +Werkzeug + +# Coronary Mesh Convolution +openmesh>=1.2.1 +potpourri3d>=0.0.8 +prettytable +trimesh>=3.15.3 +vtk>=9.2.2 diff --git a/gafl/build/geometric-algebra-transformer/gatr/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9604b1ea4d331d71d67f39178103f1b945a00f28 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .layers.attention.config import SelfAttentionConfig +from .layers.mlp.config import MLPConfig +from .nets.axial_gatr import AxialGATr +from .nets.gatr import GATr + +__version__ = "1.2.0" diff --git a/gafl/build/geometric-algebra-transformer/gatr/baselines/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/baselines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e91f2baca0662b6b197402d5875aa799837dc855 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/baselines/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .mlp import MLP +from .transformer import BaselineAxialTransformer, BaselineTransformer diff --git a/gafl/build/geometric-algebra-transformer/gatr/baselines/gcan.py b/gafl/build/geometric-algebra-transformer/gatr/baselines/gcan.py new file mode 100644 index 0000000000000000000000000000000000000000..b9efe3eadedfcd2124c74b2021a570cf56587d54 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/baselines/gcan.py @@ -0,0 +1,299 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from code by David Ruhe. + +MIT License + +Copyright (c) Microsoft Corporation. + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +import numpy as np +import torch +from cliffordlayers.cliffordalgebra import CliffordAlgebra +from cliffordlayers.nn.modules.gcan import MultiVectorAct, PGAConjugateLinear +from torch import nn +from torch_geometric.nn import MessagePassing + + +class GCAMLP(nn.Module): + """GCA-MLP model. + + As described in D. Ruhe et al, "Geometric Clifford Algebra Networks". + Based on layers from the official + [cliffordlayers code](https://github.com/microsoft/cliffordlayers/tree/main). + + This network uses the same projective geometric algebra representations as GATr, but is not + E(3)-equivariant. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_shape : tuple of int + Shape expected of input tensors, excluding the 16 components of the multivectors. + out_shape : tuple of int + Shape expected for output tensors, excluding the 16 components of the multivectors. + hidden_channels : int + Number of hidden channels. + hidden_layers : int + Number of hidden layers. + act_agg : {"linear", "sum", "mean"} + Aggregation function. + flatten : bool + If True, the network flattens the input along all dimensions except the first (batch) + and last (multivector component) dimension. Otherwise, all dimensions except for the last + two are treated as batch dimensions. + """ + + def __init__( + self, + in_shape, + out_shape, + hidden_channels, + hidden_layers, + act_agg="linear", + flatten=True, + **kwargs, + ): + super().__init__() + + if not hidden_layers > 0: + raise NotImplementedError("Only supports > 0 hidden layers") + + in_channels = np.product(in_shape) if flatten else in_shape[-1] + out_channels = np.product(out_shape) if flatten else out_shape[-1] + self.flatten = flatten + self.in_shape = in_shape + self.out_shape = out_shape + + self.pga = CliffordAlgebra((0, 1, 1, 1)) + self.model = self._make_net( + in_channels, out_channels, hidden_channels, hidden_layers, act_agg + ) + + def _make_net(self, in_channels, out_channels, hidden_channels, hidden_layers, act_agg): + """PGA-MLP code as sent by David Ruhe.""" + + all_blades = list(range(16)) + action_blades = (0, 5, 6, 7, 8, 9, 10, 15) # From David; using all blades results in NaNs + + linear_in = PGAConjugateLinear( + in_channels, + hidden_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ) + linear_out = nn.Sequential( + MultiVectorAct( + hidden_channels, + self.pga, + input_blades=all_blades, + agg=act_agg, + ), + PGAConjugateLinear( + hidden_channels, + out_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ), + ) + mlp = [ + nn.Sequential( + MultiVectorAct( + hidden_channels, + self.pga, + input_blades=all_blades, + agg=act_agg, + ), + PGAConjugateLinear( + hidden_channels, + hidden_channels, + self.pga, + input_blades=all_blades, + action_blades=action_blades, + ), + ) + for _ in range(hidden_layers - 1) + ] + return nn.Sequential(linear_in, *mlp, linear_out) + + def forward(self, inputs: torch.Tensor): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor with shape (..., 16) + Input multivectors. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivectors. + """ + input_shape = inputs.shape + if self.flatten: + # Flatten all non-batch dimensions + inputs = inputs.reshape(input_shape[0], -1, 16) + outputs = self.model(inputs) + if self.flatten: + outputs = outputs.reshape(input_shape[0], *self.out_shape, 16) + return outputs + + +class GCAGNNLayer(MessagePassing): # pylint: disable=abstract-method + """GCA-GNN layer as described in D. Ruhe et al. + + This was described in "Geometric Clifford Algebra Networks" by D. Ruhe et. al, + and in private communication from D. Ruhe. + Uses the GCAN layers in the official cliffordlayers library, pieces them together based on the + information in the paper. Follows the PyG message-passing schema. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + message_channels : int + Number of channels in the messages. + mlp_hidden_channels : int + Number of hidden channels in the MLPs. + mlp_hidden_layers : int + Number of hidden layers in the MLPs. + """ + + def __init__( + self, + in_channels, + out_channels, + message_channels, + mlp_hidden_channels, + mlp_hidden_layers, + ): + super().__init__(aggr="add", flow="source_to_target", node_dim=-3) + + # GCA-MLPs for input, output, message, and update functions + shared_kwargs = dict( + hidden_channels=mlp_hidden_channels, hidden_layers=mlp_hidden_layers, flatten=False + ) + self.message_mlp = GCAMLP((2 * in_channels,), (message_channels,), **shared_kwargs) + self.update_mlp = GCAMLP( + (in_channels + message_channels,), (out_channels,), **shared_kwargs + ) + + def forward(self, x, edge_index): # pylint: disable=arguments-differ + """Forward pass.""" + return self.propagate(edge_index, x=x) + + def message(self, x_i, x_j): # pylint: disable=arguments-differ + """Constructs message.""" + features = torch.cat([x_i, x_j], dim=1) # shape (edges, 2*node_channels, 16) + message = self.message_mlp(features) # shape (edges, message_channels, 16) + return message + + def update(self, aggr_out, x): # pylint: disable=arguments-differ + """Updates node states with aggregated messages.""" + + features = torch.cat( + [x, aggr_out], dim=1 + ) # shape (nodes, node_channels + message_channels, 16) + x = self.update_mlp(features) # shape (nodes, node_channels, 16) + return x + + +class GCAGNN(nn.Module): + """GCA-GNN model as described in D. Ruhe et al. + + The model was described in "Geometric Clifford Algebra Networks" by D.Ruhe et al., + and in private communication from D. Ruhe. + + Combines multiple GCAGNNLayers. + + This network uses the same projective geometric algebra representations as GATr, but is not + E(3)-equivariant. + + References + ---------- + D. Ruhe et al, "Geometric Clifford Algebra Networks", arXiv:2302.06594 + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + node_channels : int + Number of channels in the hidden representation for each node. + message_channels : int + Number of channels in the messages. + mlp_hidden_channels : int + Number of hidden channels in the MLPs. + mlp_hidden_layers : int + Number of hidden layers in the MLPs. + message_passing_steps : int + Number of message-passing steps / GCAGNNLayer blocks. + """ + + def __init__( + self, + in_channels, + out_channels, + node_channels, + message_channels, + mlp_hidden_channels, + mlp_hidden_layers, + message_passing_steps, + **kwargs, + ): + super().__init__() + + # Construct layers + self.layers = nn.ModuleList([]) + shared_kwargs = dict( + mlp_hidden_channels=mlp_hidden_channels, + mlp_hidden_layers=mlp_hidden_layers, + message_channels=message_channels, + ) + + # Initial step: in_channels to node_channels + self.layers.append(GCAGNNLayer(in_channels, node_channels, **shared_kwargs)) + + # Intermediate steps / layers + for _ in range(message_passing_steps - 2): + self.layers.append(GCAGNNLayer(node_channels, node_channels, **shared_kwargs)) + + # Final step: node_channels to out_channels + self.layers.append(GCAGNNLayer(node_channels, out_channels, **shared_kwargs)) + + def forward(self, x, edge_index): + """Forward pass.""" + for layer in self.layers: + x = layer(x, edge_index=edge_index) + return x diff --git a/gafl/build/geometric-algebra-transformer/gatr/baselines/mlp.py b/gafl/build/geometric-algebra-transformer/gatr/baselines/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..489973d86bd4165453148998d2985ed97e11cc0f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/baselines/mlp.py @@ -0,0 +1,40 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import List + +import numpy as np +import torch +from torch import nn + + +class MLP(nn.Module): + """A simple baseline MLP. + + Flattens all dimensions except batch and uses GELU nonlinearities. + """ + + def __init__(self, in_shape, out_shape, hidden_channels, hidden_layers): + super().__init__() + + if not hidden_layers > 0: + raise NotImplementedError("Only supports > 0 hidden layers") + + self.in_shape = in_shape + self.out_shape = out_shape + + layers: List[nn.Module] = [nn.Linear(np.product(in_shape), hidden_channels)] + for _ in range(hidden_layers - 1): + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_channels, hidden_channels)) + + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_channels, np.product(self.out_shape))) + self.mlp = nn.Sequential(*layers) + + def forward(self, inputs: torch.Tensor): + """Forward pass of baseline MLP.""" + batchsize = inputs.shape[0] + inputs = inputs.reshape(batchsize, -1) + outputs = self.mlp(inputs) + outputs = outputs.reshape(batchsize, *self.out_shape) + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/baselines/segnn.py b/gafl/build/geometric-algebra-transformer/gatr/baselines/segnn.py new file mode 100644 index 0000000000000000000000000000000000000000..dcffd7dafcf50c8eacfd40b9304181cab7e7e607 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/baselines/segnn.py @@ -0,0 +1,110 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/RobDHess/Steerable-E3-GNN/blob/1b95898f6f18204b510ae127d7f38cd29f610f4d/nbody/train_nbody.py +by Johannes Brandstetter, Rob Hesselink, Erik Bekkers at +https://github.com/RobDHess/Steerable-E3-GNN + +MIT License + +Copyright (c) 2021 Johannes Brandstetter, Rob Hesselink, Erik Bekkers + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +from e3nn.o3 import Irreps +from segnn.balanced_irreps import BalancedIrreps, WeightBalancedIrreps +from segnn.segnn.segnn import SEGNN +from torch import nn + + +def _make_segnn_irreps(vec_channels, scalar_channels): + """Creates an Irreps object for SEGNNModel given a number of O(3) vectors and scalars.""" + assert vec_channels > 0 or scalar_channels > 0 + irreps = [] + if vec_channels > 0: + irreps.append(f"{vec_channels}x1o") + if scalar_channels > 0: + irreps.append(f"{scalar_channels}x0e") + return Irreps(" + ".join(irreps)) + + +class SEGNNModel(nn.Module): + """SEGNN baseline. + + We restrict ourselves to vector and scalar inputs, as those were sufficient for our experiments. + + References + ---------- + J. Brandstetter et al, "Geometric and Physical Quantities Improve E(3) Equivariant Message + Passing", ICLR 2022 + """ + + def __init__( + self, + input_vec_channels=2, + input_s_channels=1, + output_vec_channels=1, + output_s_channels=0, + additional_message_s_channels=2, + hidden_features=128, + lmax_h=2, + lmax_attr=3, + subspace_type="weightbalanced", + layers=7, + norm="instance", + pool="avg", + task="node", + **kwargs, + ): + super().__init__() + + input_irreps = _make_segnn_irreps(input_vec_channels, input_s_channels) + output_irreps = _make_segnn_irreps(output_vec_channels, output_s_channels) + edge_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + node_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + additional_message_irreps = _make_segnn_irreps(0, additional_message_s_channels) + + if subspace_type == "weightbalanced": + hidden_irreps = WeightBalancedIrreps( + _make_segnn_irreps(0, hidden_features), node_attr_irreps, sh=True, lmax=lmax_h + ) + elif subspace_type == "balanced": + hidden_irreps = BalancedIrreps(lmax_h, hidden_features, True) + else: + raise ValueError(f"Unknown subspace type {subspace_type}") + + self.model = SEGNN( + input_irreps, + hidden_irreps, + output_irreps, + edge_attr_irreps, + node_attr_irreps, + num_layers=layers, + norm=norm, + pool=pool, + task=task, + additional_message_irreps=additional_message_irreps, + ) + + def forward(self, *inputs, **kwargs): + """Forward pass.""" + return self.model(*inputs, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/gatr/baselines/transformer.py b/gafl/build/geometric-algebra-transformer/gatr/baselines/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..072e5b86e59d89c00889697f96e59eaba8b3210e --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/baselines/transformer.py @@ -0,0 +1,557 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Baseline transformer.""" + +from functools import partial +from typing import Optional, Tuple + +import torch +from einops import rearrange +from torch import nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers import ApplyRotaryPositionalEncoding +from gatr.primitives.attention import scaled_dot_product_attention +from gatr.utils.tensors import to_nd + +# Default rearrange patterns for odd blocks +_REARRANGE_PATTERN = "... i j c -> ... j i c" + + +class BaselineLayerNorm(nn.Module): + """Baseline layer norm over all dimensions except the first.""" + + @staticmethod + def forward(inputs: torch.Tensor) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + + Returns + ------- + outputs : Tensor + Normalized inputs. + """ + return torch.nn.functional.layer_norm(inputs, normalized_shape=inputs.shape[1:]) + + +class MultiHeadQKVLinear(nn.Module): + """Compute queries, keys, and values via multi-head attention. + + Parameters + ---------- + in_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + """ + + def __init__(self, in_channels, hidden_channels, num_heads): + super().__init__() + self.num_heads = num_heads + self.linear = nn.Linear(in_channels, 3 * hidden_channels * num_heads) + + def forward(self, inputs): + """Forward pass. + + Returns + ------- + q : Tensor + Queries + k : Tensor + Keys + v : Tensor + Values + """ + qkv = self.linear(inputs) # (..., num_items, 3 * hidden_channels * num_heads) + q, k, v = rearrange( + qkv, + "... items (qkv hidden_channels num_heads) -> qkv ... num_heads items hidden_channels", + num_heads=self.num_heads, + qkv=3, + ) + return q, k, v + + +class MultiQueryQKVLinear(nn.Module): + """Compute queries, keys, and values via multi-query attention. + + Parameters + ---------- + in_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + """ + + def __init__(self, in_channels, hidden_channels, num_heads): + super().__init__() + self.num_heads = num_heads + self.q_linear = nn.Linear(in_channels, hidden_channels * num_heads) + self.k_linear = nn.Linear(in_channels, hidden_channels) + self.v_linear = nn.Linear(in_channels, hidden_channels) + + def forward(self, inputs): + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + + Returns + ------- + q : Tensor + Queries + k : Tensor + Keys + v : Tensor + Values + """ + q = rearrange( + self.q_linear(inputs), + "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels", + num_heads=self.num_heads, + ) + k = self.k_linear(inputs)[..., None, :, :] # (..., head=1, item, hidden_channels) + v = self.v_linear(inputs)[..., None, :, :] + return q, k, v + + +class BaselineSelfAttention(nn.Module): + """Baseline self-attention layer. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of input channels. + hidden_channels : int + Number of hidden channels = size of query, key, and value. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_enc_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_heads: int = 8, + pos_encoding: bool = False, + pos_enc_base: int = 4096, + multi_query: bool = True, + ) -> None: + super().__init__() + + # Store settings + self.num_heads = num_heads + self.hidden_channels = hidden_channels + + # Linear maps + qkv_class = MultiQueryQKVLinear if multi_query else MultiHeadQKVLinear + self.qkv_linear = qkv_class(in_channels, hidden_channels, num_heads) + self.out_linear = nn.Linear(hidden_channels * num_heads, out_channels) + + # Optional positional encoding + if pos_encoding: + self.pos_encoding = ApplyRotaryPositionalEncoding( + hidden_channels, item_dim=-2, base=pos_enc_base + ) + else: + self.pos_encoding = None + + def forward( + self, inputs: torch.Tensor, attention_mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor + Outputs + """ + q, k, v = self.qkv_linear(inputs) # each: (..., num_heads, num_items, num_channels, 16) + + # Rotary positional encoding + if self.pos_encoding is not None: + q = self.pos_encoding(q) + k = self.pos_encoding(k) + + # Attention layer + h = self._attend(q, k, v, attention_mask) + + # Concatenate heads and transform linearly + h = rearrange( + h, + "... num_heads num_items hidden_channels -> ... num_items (num_heads hidden_channels)", + ) + outputs = self.out_linear(h) # (..., num_items, out_channels) + + return outputs + + @staticmethod + def _attend(q, k, v, attention_mask=None): + """Scaled dot-product attention.""" + + # Add batch dimension if needed + bh_shape = q.shape[:-2] + q = to_nd(q, 4) + k = to_nd(k, 4) + v = to_nd(v, 4) + + # SDPA + outputs = scaled_dot_product_attention( + q.contiguous(), k.expand_as(q).contiguous(), v.expand_as(q), attn_mask=attention_mask + ) + + # Return batch dimensions to inputs + outputs = outputs.view(*bh_shape, *outputs.shape[-2:]) + + return outputs + + +class BaselineTransformerBlock(nn.Module): + """Baseline transformer block. + + Inputs are first processed by a block consisting of LayerNorm, multi-head self-attention, and + residual connection. Then the data is processed by a block consisting of another LayerNorm, an + item-wise two-layer MLP with GeLU activations, and another residual connection. + + Parameters + ---------- + channels : int + Number of input and output channels. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + increase_hidden_channels : int + Factor by which the key, query, and value size is increased over the default value of + hidden_channels / num_heads. + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + channels, + num_heads: int = 8, + pos_encoding: bool = False, + pos_encoding_base: int = 4096, + increase_hidden_channels=1, + multi_query: bool = True, + ) -> None: + super().__init__() + + self.norm = BaselineLayerNorm() + + # When using positional encoding, the number of scalar hidden channels needs to be even. + # It also should not be too small. + hidden_channels = channels // num_heads * increase_hidden_channels + if pos_encoding: + hidden_channels = (hidden_channels + 1) // 2 * 2 + hidden_channels = max(hidden_channels, 16) + + self.attention = BaselineSelfAttention( + channels, + channels, + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encoding, + pos_enc_base=pos_encoding_base, + multi_query=multi_query, + ) + + self.mlp = nn.Sequential( + nn.Linear(channels, 2 * channels), + nn.GELU(), + nn.Linear(2 * channels, channels), + ) + + def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor + Outputs + """ + + # Residual attention + h = self.norm(inputs) + h = self.attention(h, attention_mask) + outputs = inputs + h + + # Residual MLP + h = self.norm(outputs) + h = self.mlp(h) + outputs = outputs + h + + return outputs + + +class BaselineTransformer(nn.Module): + """Baseline transformer. + + Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an + MLP, residual connections, and normalization layers. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + hidden_channels : int + Number of hidden channels. + num_blocks : int + Number of transformer blocks. + num_heads : int + Number of attention heads. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + increase_hidden_channels : int + Factor by which the key, query, and value size is increased over the default value of + hidden_channels / num_heads. + multi_query : bool + Use multi-query attention instead of multi-head attention. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_blocks: int = 10, + num_heads: int = 8, + pos_encoding: bool = False, + pos_encoding_base: int = 4096, + checkpoint_blocks: bool = False, + increase_hidden_channels=1, + multi_query: bool = False, + ) -> None: + super().__init__() + self.checkpoint_blocks = checkpoint_blocks + self.linear_in = nn.Linear(in_channels, hidden_channels) + self.blocks = nn.ModuleList( + [ + BaselineTransformerBlock( + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encoding, + pos_encoding_base=pos_encoding_base, + increase_hidden_channels=increase_hidden_channels, + multi_query=multi_query, + ) + for _ in range(num_blocks) + ] + ) + self.linear_out = nn.Linear(hidden_channels, out_channels) + + def forward(self, inputs: torch.Tensor, attention_mask=None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor with shape (..., num_items, num_channels) + Input data + attention_mask : None or Tensor or xformers.ops.AttentionBias + Optional attention mask + + Returns + ------- + outputs : Tensor with shape (..., num_items, num_channels) + Outputs + """ + h = self.linear_in(inputs) + for block in self.blocks: + if self.checkpoint_blocks: + fn = partial(block, attention_mask=attention_mask) + h = checkpoint(fn, h) + else: + h = block(h, attention_mask=attention_mask) + outputs = self.linear_out(h) + return outputs + + +class BaselineAxialTransformer(nn.Module): + """Baseline axial transformer for data with two token dimensions. + + Combines num_blocks transformer blocks, each consisting of multi-head self-attention layers, an + MLP, residual connections, and normalization layers. + + Assumes input data with shape `(..., num_items_1, num_items_2, num_channels, [16])`. + + The first, third, fifth, ... block computes attention over the `items_2` axis. The other blocks + compute attention over the `items_1` axis. Positional encoding can be specified separately for + both axes. + + Parameters + ---------- + in_channels : int + Number of input channels. + out_channels : int + Number of output channels. + hidden_channels : int + Number of hidden channels. + num_blocks : int + Number of transformer blocks. + num_heads : int + Number of attention heads. + pos_encodings : tuple of bool + Whether to apply rotary positional embeddings along the item dimensions to the scalar keys + and queries. + pos_encoding_base : int + Maximum frequency used in positional encodings. (The minimum frequency is always 1.) + collapse_dims : tuple of bool + Whether batch and token dimensions will be collapsed to support xformers block attention. + The first element of this tuple describes the behaviour in the 0th, 2nd, ... block, the + second element in the 1st, 3rd, ... block (where the axes are reversed). + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + hidden_channels: int, + num_blocks: int = 20, + num_heads: int = 8, + pos_encodings: Tuple[bool, bool] = (False, False), + pos_encoding_base: int = 4096, + collapse_dims: Tuple[bool, bool] = (False, False), + ) -> None: + super().__init__() + self.linear_in = nn.Linear(in_channels, hidden_channels) + self.blocks = nn.ModuleList( + [ + BaselineTransformerBlock( + hidden_channels, + num_heads=num_heads, + pos_encoding=pos_encodings[(block + 1) % 2], + pos_encoding_base=pos_encoding_base, + ) + for block in range(num_blocks) + ] + ) + self.linear_out = nn.Linear(hidden_channels, out_channels) + self._collapse_dims_for_even_blocks, self._collapse_dims_for_odd_blocks = collapse_dims + + def forward(self, inputs: torch.Tensor, attention_mask: Optional[Tuple] = None) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + inputs : Tensor with shape (..., num_items1, num_items2, num_channels) + Input data + attention_mask : None or tuple of torch.Tensor + Optional attention masks + + Returns + ------- + outputs : Tensor with shape (..., num_items1, num_items2, num_channels) + Outputs + """ + + h = self.linear_in(inputs) + + for i, block in enumerate(self.blocks): + # For first, third, ... block, we want to perform attention over the first token + # dimension. We implement this by transposing the two item dimensions. + if i % 2 == 1: + h, input_batch_dims = self._reshape_data_before_odd_blocks(h) + else: + h, input_batch_dims = self._reshape_data_before_even_blocks(h) + + # Attention masks will also be different + if attention_mask is None: + this_attention_mask = None + else: + this_attention_mask = attention_mask[(i + 1) % 2] + + h = block(h, attention_mask=this_attention_mask) + + # Transposing back to standard axis order + if i % 2 == 1: + h = self._reshape_data_after_odd_blocks(h, input_batch_dims) + else: + h = self._reshape_data_after_even_blocks(h, input_batch_dims) + + outputs = self.linear_out(h) + + return outputs + + def _reshape_data_before_odd_blocks(self, h): + # Transpose token axes + h = rearrange(h, _REARRANGE_PATTERN) # (axis2, axis1, ...) + + # Prepare uncollapsing + input_batch_dims = h.shape[:2] + + # Collapse dimensions + if self._collapse_dims_for_odd_blocks: + h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...) + + return h, input_batch_dims + + def _reshape_data_after_odd_blocks(self, h, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_odd_blocks: + h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...) + + # Re-transpose token axes + h = rearrange(h, _REARRANGE_PATTERN) # (axis1, axis2, ...) + + return h + + def _reshape_data_before_even_blocks(self, h): + # Prepare un-collapsing + input_batch_dims = h.shape[:2] + + # Collapse + if self._collapse_dims_for_even_blocks: + h = h.reshape(-1, *h.shape[2:]) # (axis2 * axis1, ...) + + return h, input_batch_dims + + def _reshape_data_after_even_blocks(self, h, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_even_blocks: + h = h.reshape(*input_batch_dims, *h.shape[1:]) # (axis2, axis1, ...) + + return h diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d534ef3169328c9d075fa26f053c9f6de9e1bc6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .base_experiment import BaseExperiment +from .base_wrapper import BaseWrapper diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eafe209d6241d57b778eee81e437bf1a313a970d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .dataset import InMemoryVesselDataset, NumberedVesselDataset, RotationDataset +from .experiment import ArteryExperiment +from .wrappers import ArteryBaselineWrapper, ArteryGATrWrapper diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/dataset.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc4317480743d71d6e049f0b04e4b2b57a06fdd --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/dataset.py @@ -0,0 +1,55 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import os +import re + +import numpy as np +import scipy +import torch +from coronary_mesh_convolution.datasets import InMemoryVesselDataset +from torch.utils.data import Dataset + + +class NumberedVesselDataset(InMemoryVesselDataset): + """Artery dataset with added shape id attribute.""" + + @staticmethod + def load_process_hdf5(path): + """Wrap super method with adding shape id.""" + _, sample = os.path.split(path) + data = InMemoryVesselDataset.load_process_hdf5(path) + data.shape_id = int(re.match(r"sample_(\d+)", sample).group(1)) + return data + + +class RotationDataset(Dataset): + """A dataset containing random (S)O(3) elements. + + Parameters + ---------- + num : int + Size of the dataset (number of rotations) + special : bool + If True, samples from the Haar measure on SO(3); otherwise, on O(3) + seed : int + numpy random seed + """ + + def __init__(self, num, special, seed): + super().__init__() + if special: + sampler = scipy.stats.special_ortho_group + else: + sampler = scipy.stats.ortho_group + random_state = np.random.RandomState(seed=seed) + self.data = torch.tensor( + sampler.rvs(3, size=num, random_state=random_state), dtype=torch.float32 + ) + + def __len__(self): + """Dataset size.""" + return len(self.data) + + def __getitem__(self, idx): + """Return an item from the dataset.""" + return self.data[idx] diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/experiment.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..682c60e7af6ce44deefa06f95e3280d74d5a4ac8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/experiment.py @@ -0,0 +1,259 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from pathlib import Path + +import pandas as pd +import torch +import torch_geometric +from coronary_mesh_convolution.transforms import InletGeodesics, RemoveFlowExtensions +from coronary_mesh_convolution.utils.metrics import Metrics + +from gatr.experiments import BaseExperiment +from gatr.experiments.arteries.dataset import NumberedVesselDataset, RotationDataset +from gatr.utils.logger import logger + +LABEL_SCALE = 53.8360 # the sqrt of average squared norm of training label vectors + + +class ArteryExperiment(BaseExperiment): + """Experiment manager for wall-shear-stress estimation in arteries. + + The dataset was introduced and is described in Suk et al, "Mesh Convolutional Neural Networks + for Wall Shear Stress Estimation in 3D Artery Models". + + References + ---------- + J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in + 3D Artery Models", arXiv:2109.04797 + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + super().__init__(cfg) + self._criterion = torch.nn.MSELoss() + + # Data transforms + transforms = [ + torch_geometric.transforms.GenerateMeshNormals(), + InletGeodesics(), + RemoveFlowExtensions(factor=(4.0, 1.0)), + ] + self.transform = torch_geometric.transforms.Compose(transforms) + self.rotations = RotationDataset(2000, special=False, seed=123) + + def rotate_sample(self, data): + """Rotate data sample with pre-sampled rotation matrices.""" + r = self.rotations[data.shape_id[0]] + data.pos = data.pos @ r.T + data.norm = data.norm @ r.T + data.y = data.y @ r.T + return data + + def _load_dataset(self, tag): + """Loads dataset. + + References + ---------- + J. Suk et al., "Mesh Convolutional Neural Networks for Wall Shear Stress Estimation in + 3D Artery Models", arXiv:2109.04797 + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + + # Train / validation / test splits from Suk et al + split = {"train": [0, 1600], "val": [1600, 1799], "eval": [1799, 1999]}[tag] + + if (self.cfg.data.rotate_train and tag == "train") or ( + self.cfg.data.rotate_test and tag in ["val", "eval"] + ): + transform = self.rotate_sample + else: + transform = None + + # Load dataset + dataset = NumberedVesselDataset( + Path(self.cfg.data.data_dir), + "*.hdf5", + split, + tag, + pre_transform=self.transform, + transform=transform, + ) + + # Subsample dataset if requested + if tag == "train" and self.cfg.data.subsample is not None and self.cfg.data.subsample < 1.0: + n = int(round(self.cfg.data.subsample * len(dataset))) + dataset = dataset.index_select(slice(n)) + + # Logging + logger.info(f"Loaded dataset partition {tag} with length {len(dataset)}") + + return dataset + + def _prep_data(self, data, device=None): + """Data preparation during training loop, e.g. to move data to correct device and dtype.""" + + if device is None: + device = self.device + + # Only move relevant features to GPU and float16 + data.pos = data.pos.to(device) + data.norm = data.norm.to(device) + data.geo = data.geo.to(device) + data.y = data.y.to(device) + + # NaN debugging + assert torch.all(torch.isfinite(data.pos)) + assert torch.all(torch.isfinite(data.norm)) + assert torch.all(torch.isfinite(data.geo)) + assert torch.all(torch.isfinite(data.y)) + + # Mask should also be on GPU, but remain as bool + data.mask = data.mask.to(device) + data.batch = data.batch.to(device) + + return (data,) + + def _forward(self, *data): + """Model forward pass. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + + # Forward pass + assert self.model is not None + data = data[0] + y_pred = self.model(data) + + # NaN debugging + assert torch.all(torch.isfinite(y_pred)) + + # Compute loss + y = data.y.view(*y_pred.shape) + y_normalized = y / LABEL_SCALE # normalize labels + y_pred_unnormalized = y_pred * LABEL_SCALE # unnormalize predictions + mse_normalized = self._criterion(y_pred[:, data.mask, :], y_normalized[:, data.mask, :]) + mse = self._criterion(y_pred_unnormalized[:, data.mask, :], y[:, data.mask, :]) + loss = mse_normalized + + # Additional metrics + metrics = dict(mse=mse.item(), mse_normalized=mse_normalized.item()) + + return loss, metrics + + @torch.no_grad() + def _compute_metrics(self, dataloader): + """Given a dataloader, computes all relevant metrics. To be implemented by subclasses. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Dataloader. + + Returns + ------- + metrics : dict with str keys and float values + Metrics computed from dataset. + """ + + # Move to eval mode and eval device + assert self.model is not None + self.model.eval() + eval_device = torch.device(self.cfg.training.eval_device) + self.model = self.model.to(eval_device) + + metrics_model = Metrics([dataloader]) + results = [] + + # Loop over dataset and compute metrics + for data in dataloader: + data = self._prep_data(data)[0] + model_output = self.model(data) + y_pred_batch = model_output[0] * LABEL_SCALE # Scale as ground truth, remove batch idx + num_meshes = data.batch.max() + 1 + for mesh_i in range(num_meshes): + batch_mask = data.batch == mesh_i + # Mask out one particular mesh, remove the in/outlets + prediction = y_pred_batch[batch_mask & data.mask] + label = data.y[batch_mask & data.mask] + _, maximum, mean, _ = metrics_model.absolute_differences(prediction, label) + scale_max, scale_median = metrics_model.scale(label) + approximation_error = metrics_model.approximation_error(prediction, label) + mse = self._criterion(prediction, label) + mesh_results = dict( + delta_max=maximum.item(), + delta_mean=mean.item(), + nmae=(mean / metrics_model.M).item(), + approximation_error=approximation_error.item(), + scale_max=scale_max.item(), + scale_median=scale_median.item(), + mse=mse.item(), + ) + results.append(mesh_results) + df = pd.DataFrame(results) + metrics = {} + for metric, series in df.items(): + metrics[f"{metric}"] = series.mean() + metrics[f"{metric}_median"] = series.median() + metrics[f"{metric}_q75"] = series.quantile(0.75) + metrics["loss"] = metrics["mse"] + + # Move model back to training mode and training device + self.model.train() + self.model = self.model.to(self.device) + + return metrics + + @property + def _eval_dataset_tags(self): + """Eval dataset tags. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + return {"eval"} + + def _make_data_loader(self, dataset, batch_size, shuffle): + """Creates a data loader. + + Parameters + ---------- + dataset : torch.nn.utils.data.Dataset + Dataset. + batch_size : int + Batch size. + shuffle : bool + Whether the dataset is shuffled. + + Returns + ------- + dataloader + Data loader. + """ + return torch_geometric.data.DataLoader( + dataset, batch_size=batch_size, shuffle=shuffle, num_workers=0, pin_memory=False + ) diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/wrappers.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..60b236f35ef22766cef83d5ab954b8d22f3d7816 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/arteries/wrappers.py @@ -0,0 +1,153 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import nn +from xformers.ops.fmha import BlockDiagonalMask + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_oriented_plane, embed_point, embed_scalar, extract_translation + + +def build_attention_mask(inputs): + """Construct attention mask from pytorch geometric batch. + + Parameters + ---------- + inputs : torch_geometric.data.Batch + Data batch. + + Returns + ------- + attention_mask : xformers.ops.fmha.BlockDiagonalMask + Block-diagonal attention mask: within each sample, each token can attend to each other + token. + """ + return BlockDiagonalMask.from_seqlens(torch.bincount(inputs.batch).tolist()) + + +class ArteryBaselineWrapper(nn.Module): + """Wraps around simple baselines (like a Transformer) for the artery experiment. + + We use the following parameterization of the artery mesh: + - the node positions of the arterial mesh + - the mesh normals + - the geodesic distance to the inlet + + Parameters + ---------- + net : torch.nn.Module + Model that accepts inputs with 7 channels and returns outputs with 3 channels. + """ + + def __init__(self, net): + super().__init__() + self.net = net + + def forward(self, inputs): + """Wrapped forward pass.""" + mask = build_attention_mask(inputs) + x = torch.cat([inputs.pos, inputs.norm, inputs.geo[:, None]], 1)[None] + return self.net(x, attention_mask=mask) + + +class ArteryGATrWrapper(BaseWrapper): + """Wraps around GATr for the arterial wall-shear-stress prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + GATr model that accepts inputs with 3 multivector channels and 1 scalar channel, and + returns outputs with 1 multivector channel and 1 scalar channel. + """ + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def build_attention_mask( + self, + inputs, + mv=None, + s=None, + ): + """Construct block-diagonal attention mask.""" + return build_attention_mask(inputs) + + def embed_into_ga(self, inputs): + """Embeds raw artery data into the geometric algebra. + + We use the following parameterization of the artery mesh: + - the node positions of the arterial mesh, represented as points + - the mesh normals, represented as oriented planes + - the geodesic distance to the inlet, represented as scalars + + Parameters + ---------- + inputs : torch_geometric.data.Batch + Raw artery data. + + Returns + ------- + multivectors : torch.Tensor with shape (batchsize * num_items, num_mv_channels, 16) + Multivector embeddings of the geometric information in the dataset. + scalars : torch.Tensor with shape (batchsize * num_items, num_s_channels) + Auxiliary scalars, which in this dataset are just dummy placeholders. + """ + + # Get interesting features from PyG object + num_items = len(inputs.pos) + pos = inputs.pos.reshape(1, num_items, 1, 3) # (batch, items, channels, 3) + mesh_normals = inputs.norm.reshape(1, num_items, 1, 3) # (batch, items, channels, 3) + inlet_distance = inputs.geo.reshape(1, num_items, 1, 1) # (batch, items, channels, 1) + + # NaN debugging + assert torch.all(torch.isfinite(pos)) + assert torch.all(torch.isfinite(mesh_normals)) + assert torch.all(torch.isfinite(inlet_distance)) + + # Embed in GA + positions = embed_point(pos) + mesh_normals = embed_oriented_plane(mesh_normals, pos) + inlet_distance = embed_scalar(inlet_distance) + + # NaN debugging + assert torch.all(torch.isfinite(positions)) + assert torch.all(torch.isfinite(mesh_normals)) + assert torch.all(torch.isfinite(inlet_distance)) + + # Concatenate along channel dimension + mv = torch.concatenate( + [positions, mesh_normals, inlet_distance], dim=2 + ) # (batch, items, 3, 16) + + # Dummy scalar + s = torch.zeros(1, num_items, 1, device=mv.device, dtype=mv.dtype) + + return mv, s + + def extract_from_ga(self, multivector, scalars): + """Extracts the predicted wall shear stress from the output multivectors. + + We parameterize the wall shear stress as translation vectors. + + Parameters + ---------- + multivector : torch.Tensor with shape (1, batchsize * num_items, num_mv_channels, 16) + Multivector outputs. + scalars : torch.Tensor with shape (1, batchsize * num_items, num_s_channels) + Scalar outputs. + + Returns + ------- + wss : torch.Tensor with shape (1, batchsize * num_items, 3) + Predicted wall shear stress vectors. + regularization : None + Regularization term. As there is no regularizer in this experiment, we return None. + """ + # Check channels of inputs. Object numbers are free. + assert multivector.shape[0] == scalars.shape[0] == 1 + assert multivector.shape[2:] == (1, 16) + + # Extract wall shear stress + wss = extract_translation(multivector[:, :, 0, :]) # (1, objects, 3) + + return wss, None diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/base_experiment.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/base_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..80665574db9cf102c6f72a07860fbc31dca06c84 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/base_experiment.py @@ -0,0 +1,774 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import logging +import time +from collections import defaultdict +from contextlib import nullcontext +from pathlib import Path +from typing import Dict, Optional + +import matplotlib +import mlflow +import numpy as np +import pandas as pd +import seaborn as sns +import torch +from hydra.core.config_store import ConfigStore +from hydra.utils import instantiate +from omegaconf import OmegaConf +from torch import nn +from torch.utils.data import DataLoader +from torch_ema import ExponentialMovingAverage +from tqdm import tqdm, trange + +import gatr.primitives.attention +import gatr.utils.logger +from gatr.layers import SelfAttentionConfig +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.logger import logger +from gatr.utils.misc import NaNError, flatten_dict, frequency_check, get_batchsize, get_device +from gatr.utils.mlflow import log_mlflow +from gatr.utils.plotting import MATPLOTLIB_PARAMS + +cs = ConfigStore.instance() +cs.store(name="base_attention", node=SelfAttentionConfig) +cs.store(name="base_mlp", node=MLPConfig) + + +class BaseExperiment: + """Base experiment manager class. + + To be subclassed by experiment-specific manager classes. + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + # Store config + self.cfg = cfg + + # Device, dtype, backend + self.device, self.dtype = self._init_backend() + + # Initialize state + self.model: Optional[nn.Module] = None + self.ema = None + self.optim = None + self.scheduler = None + + self.metrics = {} + self._best_state = None + self._training_start_time: Optional[float] = None + + # Initialize folder and logger + self._initialize_experiment_folder() + self._initialize_logger() + self._silence_the_lambs() + + # Training hooks: list of (state, hook_function) + self._hooks = [] + + def __call__(self, train=True, evaluate=True): + """Performs experiment as outlined below. + + - initializes all the logistics + - instantiates model (if necessary) + - loads checkpoint (if applicable) + - trains model (if `train`) + - evaluates model (if `eval`) + + Parameters + ---------- + train : bool + Whether to train the model. + evaluate : bool + Whether to evaluate the model. + """ + + experiment_id = self._initialize_experiment() + + with mlflow.start_run(experiment_id=experiment_id, run_name=self.cfg.run_name): + self._save_config() + + # Create / load model + if self.model is None: + self.create_model() + self.load_model() + + # Train + if train: + self.train() + # Save model + self.save_model("model_final.pt") + + # Evaluate + if evaluate: + self.evaluate() + + logger.info("Anders nog iets?") + return self.metrics + + def create_model(self): + """Create self.model according to the specification in self.cfg.""" + + # Create model + self.model = self._create_model() + assert self.model is not None + self.optim, self.scheduler = self._create_optimizer_and_scheduler() + + # Report number of parameters + num_parameters = sum(p.numel() for p in self.model.parameters() if p.requires_grad) + log_mlflow("efficiency.num_parameters", float(num_parameters), step=0) + logger.info(f"Model has {num_parameters / 1e6:.2f}M learnable parameters") + + # Create exponential moving average object + if self.cfg.training.ema: + logger.info("Using EMA for validation and eval") + self.ema = ExponentialMovingAverage( + self.model.parameters(), decay=self.cfg.training.ema_decay + ) + else: + logger.debug("Not using EMA") + self.ema = None + + def load_model(self, checkpoint=None): + """Loads a model checkpoint from disk. + + Parameters + ---------- + checkpoint : None or str or pathlib.Path + Path to checkpoint. If None, self.cfg.checkpoint is used. + """ + + # If model hasn't been created yet, do that first + if self.model is None: + self.create_model() + assert self.model is not None + + if checkpoint is None: + checkpoint = self.cfg.checkpoint + + if checkpoint is not None: + logger.info(f"Loading model checkpoint from {checkpoint}") + state_dict = torch.load(checkpoint, map_location="cpu") + self.model.load_state_dict(state_dict) + + if self.cfg.training.ema: + ema_checkpoint = checkpoint.replace(".pt", "_ema.pt") + logger.info(f"Loading EMA checkpoint from {ema_checkpoint}") + state_dict = torch.load(ema_checkpoint, map_location="cpu") + assert self.ema is not None + self.ema.load_state_dict(state_dict) + + def train(self): + """High-level training function.""" + assert self.model is not None + + logger.info("Starting training") + + # Prepare data + train_data = self._load_dataset("train") + train_loader = self._make_data_loader( + train_data, batch_size=self.cfg.training.batchsize, shuffle=True + ) + val_data = self._load_dataset("val") + eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize) + val_loader = self._make_data_loader(val_data, batch_size=eval_batchsize, shuffle=False) + + # Training + num_epochs = (self.cfg.training.steps - 1) // ( + (len(train_data) - 1) // self.cfg.training.batchsize + 1 + ) + 1 + logger.info( + f"Training for {self.cfg.training.steps} steps, that is, {num_epochs} epochs on a " + f"dataset of size {len(train_data)} with batchsize {self.cfg.training.batchsize}" + ) + + # Prepare book-keeping + self._best_state = {"state_dict": None, "loss": None, "step": None} + self._training_start_time = time.time() + + # GPU + self.model = self.model.to(self.device) + if self.ema: + self.ema.to(self.device) + + # Loop over epochs + step = 0 + for epoch in trange( + num_epochs, desc="Training epochs", disable=not self.cfg.training.progressbar + ): + log_mlflow("train.epoch", epoch, step=step) + epoch_start = time.perf_counter() + self.model.train() + + # Loop over steps + for data in train_loader: + self._step(data, step, val_data, val_loader) + if step >= self.cfg.training.steps: + break + step += 1 + + logger.debug(f"Finished epoch {epoch} in {time.perf_counter() - epoch_start} seconds") + + logger.debug("Finished training") + + # Final validation loop + if ( + self.cfg.training.validate_every_n_steps is not None + and self.cfg.training.validate_every_n_steps > 0 + ): + self.validate(val_loader, step) + + # Wrap up early stopping + if ( + self.cfg.training.early_stopping + and self._best_state["step"] is not None + and self._best_state["step"] < step + ): + logger.info( + f'Early stopping after step {self._best_state["step"]} ' + f'with validation loss {self._best_state["loss"]}' + ) + self.model.load_state_dict(self._best_state["state_dict"]) + else: + logger.debug("Not using early stopping") + + def validate(self, dataloader, step): + """Runs validation loop, logs results, and may store state dict for early stopping. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Validation dataloader. + step : int + Current step number. + """ + assert self.model is not None + + # Compute validation metrics, using EMA if available + if self.ema is not None: + with self.ema.average_parameters(): + metrics = self._compute_metrics(dataloader) + else: + metrics = self._compute_metrics(dataloader) + + # Log + self.metrics["val"] = metrics + logger.info(f"Validation loop at step {step}:") + for key, value in metrics.items(): + log_mlflow(f"val.{key}", value, step=step) + logger.info(f" {key} = {value}") + + # Early stopping: compare val loss to last val loss + new_val_loss = metrics["loss"] + assert self._best_state is not None + if self._best_state["loss"] is None or new_val_loss < self._best_state["loss"]: + self._best_state["loss"] = new_val_loss + self._best_state["state_dict"] = self.model.state_dict().copy() + self._best_state["step"] = step + + def evaluate(self): + """Evaluates self.model on all eval datasets and logs the results.""" + + # Should we evaluate with EMA in addition to without? + ema_values = [False] + if self.ema is not None: + ema_values.append(True) + + # Loop over evaluation datasets + dfs = {} + for tag in self._eval_dataset_tags: + dataset = self._load_dataset(tag) + eval_batchsize = self.cfg.training.get("eval_batchsize", self.cfg.training.batchsize) + dataloader = self._make_data_loader(dataset, batch_size=eval_batchsize, shuffle=False) + + # Loop over EMA on / off + for ema in ema_values: + # Effective tag name + full_tag = (tag + "_ema") if ema else tag + + # Run evaluation + if ema: + with self.ema.average_parameters(): + metrics = self._compute_metrics(dataloader) + else: + metrics = self._compute_metrics(dataloader) + + # Log results + self.metrics[full_tag] = metrics + logger.info(f"Ran evaluation on dataset {full_tag}:") + for key, val in metrics.items(): + logger.info(f" {key} = {val}") + log_mlflow(f"eval.{full_tag}.{key}", val) + + # Store results in csv file + # Pandas does not like scalar values, have to be iterables + test_metrics_ = {key: [val] for key, val in metrics.items()} + df = pd.DataFrame.from_dict(test_metrics_) + df.to_csv(Path(self.cfg.exp_dir) / "metrics" / f"eval_{full_tag}.csv", index=False) + dfs[full_tag] = df + return dfs + + def save_model(self, filename=None): + """Save model in experiment folder. + + Parameters + ---------- + filename : None or str + Filename to save the model to. + """ + + assert self.model is not None + if filename is None: + filename = "model.pt" + + model_path = Path(self.cfg.exp_dir) / "models" / filename + logger.info(f"Saving model at {model_path}") + torch.save(self.model.state_dict(), model_path) + + if self.ema is not None: + ema_path = Path(self.cfg.exp_dir) / "models" / filename.replace(".pt", "_ema.pt") + logger.debug(f"Saving EMA model at {ema_path}") + assert ema_path != model_path + torch.save(self.ema.state_dict(), ema_path) + + def register_hook(self, function, step=None, every_steps=None): + """Registers a hook. + + Hooks are functions called either at a specific step or every n steps during training. + """ + assert (step is None) != (every_steps is None) + self._hooks.append((step, every_steps, function)) + + def _init_backend(self): + """Initializes device, dtype, and attention implementation.""" + + # Device + device = get_device() + logger.debug(f"Training on {device}") + + # Dtype + if self.cfg.training.float16 and torch.cuda.is_bf16_supported(): + dtype = torch.bfloat16 + logger.info("Training on bfloat16") + elif self.cfg.training.float16: + dtype = torch.float16 + logger.info("Training on float16 (bfloat16 is not supported by environment)") + else: + dtype = torch.float32 + logger.info("Training on float32") + + # Attention implementation + torch.backends.cuda.enable_flash_sdp(self.cfg.training.enable_flash_sdp) + torch.backends.cuda.enable_math_sdp(self.cfg.training.enable_math_sdp) + torch.backends.cuda.enable_mem_efficient_sdp(self.cfg.training.enable_mem_efficient_sdp) + if self.cfg.training.force_xformers: + logger.debug("Forcing use of xformers' attention implementation") + gatr.primitives.attention.FORCE_XFORMERS = True + + return device, dtype + + def _initialize_experiment(self): + """Initialize experiment folder (and plenty of other initialization thingies).""" + + # Initialize MLflow experiment + experiment_id = self._initialize_mlflow() + + # Silence other loggers (thanks MLflow) + self._silence_the_lambs() + + # Re-initialize logger - this is annoying, something in the way that MLflow interacts with + # logging means that we otherwise get duplicate logging to stdout + self._initialize_logger() + + # Print config to log + logger.info(f"Running experiment at {self.cfg.exp_dir}") + logger.debug(f"Config: \n{OmegaConf.to_yaml(self.cfg)}") + + # Set random seed + torch.random.manual_seed(self.cfg.seed) + np.random.seed(self.cfg.seed) + + # Initialize plotting + self._init_plt() + + return experiment_id + + def _initialize_experiment_folder(self): + """Creates experiment folder.""" + + exp_dir = Path(self.cfg.exp_dir).resolve() + subfolders = [ + exp_dir / "models", + exp_dir / "figures", + exp_dir / "metrics", + exp_dir / "data", + ] + + # Create experiment subfolders (main folder will be automatically created as well) + for subdir in subfolders: + if subdir.exists(): + logger.warning(f"Warning: directory {subdir} already exists!") + subdir.mkdir(parents=True, exist_ok=True) + + def _initialize_logger(self): + """Initializes logging.""" + + # In sweeps (multiple experiments in one job) we don't want to set up the handlers again + if gatr.utils.logger.logging_initialized: + logger.info("Logger already initialized - hi again!") + return + + logger.setLevel(logging.DEBUG if self.cfg.debug else logging.INFO) + formatter = logging.Formatter( + "[%(asctime)-19.19s %(levelname)-1.1s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S" + ) + + file_handler = logging.FileHandler(Path(self.cfg.exp_dir) / "output.log") + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + logger.addHandler(stream_handler) + + # This is important to avoid duplicate log outputs + # See https://stackoverflow.com/questions/7173033/duplicate-log-output-when-using-python-logging-module # pylint:disable=line-too-long + logger.propagate = False + + gatr.utils.logger.logging_initialized = True + logger.info("Hoi.") + + def _initialize_mlflow(self): + """Initializes all things related to MLflow tracking.""" + + # Set up MLflow tracking location + Path(self.cfg.mlflow.db).parent.mkdir(exist_ok=True) + mlflow.set_tracking_uri(f"sqlite:///{Path(self.cfg.mlflow.db).resolve()}") + + # Set up MLflow experiment + Path(self.cfg.mlflow.artifacts).mkdir(exist_ok=True) + try: + experiment_id = mlflow.create_experiment( + self.cfg.exp_name, + artifact_location=f"file:{Path(self.cfg.mlflow.artifacts).resolve()}", + ) + logger.info(f"Created experiment {self.cfg.exp_name} with ID {experiment_id}") + except mlflow.exceptions.MlflowException: + pass # Experiment exists already + + # Set MLflow experiment details + experiment = mlflow.set_experiment(self.cfg.exp_name) + experiment_id = experiment.experiment_id + artifact_loc = experiment.artifact_location + + logger.info( + f"Set experiment {self.cfg.exp_name} with ID {experiment_id}," + f" artifact location {artifact_loc}" + ) + + return experiment_id + + @staticmethod + def _silence_the_lambs(): + """Silences other loggers.""" + for name, other_logger in logging.root.manager.loggerDict.items(): + if not "gatr_experiment" in name: + other_logger.level = logging.WARNING + + @staticmethod + def _init_plt(): + """Initializes matplotlib's rcparams to look good.""" + + sns.set_style("whitegrid") + matplotlib.rcParams.update(MATPLOTLIB_PARAMS) + + def _save_config(self): + """Stores the config in the experiment folder and tracks it with mlflow.""" + + # Save config + config_filename = Path(self.cfg.exp_dir) / "config.yml" + logger.info(f"Saving config at {config_filename}") + with open(config_filename, "w", encoding="utf-8") as file: + file.write(OmegaConf.to_yaml(self.cfg)) + + # Store config as MLflow params + for key, value in flatten_dict(self.cfg).items(): + log_mlflow(key, value, kind="param") + + def _create_model(self): + """Creates the model from the config. + + Returns + ------- + model : torch.nn.Module + A randomly initialized model, following the specification in self.cfg.model + """ + + # Hydra magic! + return instantiate(self.cfg.model) + + def _create_optimizer_and_scheduler(self): + """Creates optimizer and scheduler. + + Returns + ------- + optim : torch.optim.Optimizer + Adam optimizer for the parameters of self.model. + sched : torch.optim.lr_scheduler.LRScheduler + Exponential LR scheduler for optim. + """ + + optim = torch.optim.Adam( + self.model.parameters(), + lr=self.cfg.training.lr, + weight_decay=self.cfg.training.weight_decay, + ) + + num_scheduler_steps = self.cfg.training.steps // self.cfg.training.update_lr_every_n_steps + if num_scheduler_steps > 0: + gamma = self.cfg.training.lr_decay ** (1 / num_scheduler_steps) + else: + gamma = 1.0 + scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=gamma) + + return optim, scheduler + + def _make_data_loader(self, dataset, batch_size, shuffle): + """Creates a data loader. + + Parameters + ---------- + dataset : torch.nn.utils.data.Dataset + Dataset. + batch_size : int + Batch size. + shuffle : bool + Whether the dataset is shuffled. + + Returns + ------- + dataloader + Data loader. + """ + return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle) + + def _prep_data(self, data, device=None): + """Data preparation during training loop, e.g. to move data to correct device and dtype.""" + if isinstance(data, (tuple, list)): + data = tuple(x.to(device or self.device) for x in data) + elif isinstance(data, dict): + data = ({k: x.to(device or self.device) for k, x in data.items()},) + else: + data = (data.to(device or self.device),) + + return data + + def _step(self, data, step, val_data, val_loader): + """Everything that that may happen per step.""" + + # Move data to GPU, and other and other data prep stuff + data = self._prep_data(data) + + # Forward pass + with torch.autocast( + device_type="cuda", dtype=self.dtype, enabled=self.cfg.training.float16 + ): + ctx = torch.autograd.detect_anomaly if self.cfg.training.detect_anomaly else nullcontext + with ctx(): + loss, metrics = self._forward(*data) + + # Optimizer step + grad_norm = self._optimizer_step(loss) + + # Post-step hooks: logging, validating, checkpoint saving, etc + self._post_step(loss, metrics, grad_norm, step, val_data, val_loader) + + def _post_step(self, loss, metrics, grad_norm, step, val_data, val_loader): + # Log loss and metrics + self._log(loss, metrics, grad_norm, step) + + # Debugging output + if step == 0: + logger.info(f"Finished first forward pass with loss {loss.item()}") + + # Validation loop + if frequency_check(step, self.cfg.training.validate_every_n_steps, skip_initial=True): + logger.info(f"Starting validation at step {step}") + self.validate(val_loader, step) + + # Plotting + if frequency_check( + step, self.cfg.training.plot_every_n_steps, include_fractional=(0.01, 0.1) + ): + self.visualize(val_data, step) + + # Save model checkpoint + if frequency_check(step, self.cfg.training.save_model_every_n_steps, skip_initial=True): + self.save_model(f"model_step_{step}.pt") + + # LR scheduler + if frequency_check(step, self.cfg.training.update_lr_every_n_steps, skip_initial=True): + self.scheduler.step() + logger.debug(f"Decaying LR to {self.scheduler.get_last_lr()[0]}") + log_mlflow("train.lr", self.scheduler.get_last_lr()[0], step=step) + + # Custom hooks + for hook_step, hook_every_step, hook in self._hooks: + if hook_step == step or frequency_check(step, hook_every_step): + hook(model=self.model, step=step, experiment=self) + + def _optimizer_step(self, loss): + """Optimizer step and gradient norm clipping.""" + + assert self.optim is not None + if not torch.isfinite(loss): + raise NaNError("NaN in loss!") + + self.optim.zero_grad() + loss.backward() + + # Grad norm clipping + try: + clip_norm = self.cfg.training.clip_grad_norm + grad_norm = torch.nn.utils.clip_grad_norm_( + self.model.parameters(), clip_norm, error_if_nonfinite=True + ) + grad_norm = grad_norm.cpu().item() + except RuntimeError as e: + for n, p in self.model.named_parameters(): + if not torch.isfinite(p.grad.flatten().norm()): + print(f"Non-finite grad in {n}") + raise e + + self.optim.step() + if self.ema is not None: + self.ema.update() + + return grad_norm + + def _compute_metrics(self, dataloader): + """Given a dataloader, computes all relevant metrics. Can be adapted by subclasses. + + Parameters + ---------- + dataloader : torch.utils.data.DataLoader + Dataloader. + + Returns + ------- + metrics : dict with str keys and float values + Metrics computed from dataset. + """ + + # Move to eval mode and eval device + assert self.model is not None + self.model.eval() + eval_device = torch.device(self.cfg.training.eval_device) + self.model = self.model.to(eval_device) + + aggregate_metrics: Dict[str, float] = defaultdict(float) + + # Loop over dataset and compute error + for data in tqdm(dataloader, disable=False, desc="Evaluating"): + data = self._prep_data(data, device=eval_device) + + # Forward pass + loss, metrics = self._forward(*data) + + # Weight for this batch (last batches may be smaller) + batchsize = get_batchsize(data[0]) + weight = batchsize / len(dataloader.dataset) + + # Book-keeping + aggregate_metrics["loss"] += loss.item() * weight + for key, val in metrics.items(): + aggregate_metrics[key] += val * weight + + # Move model back to training mode and training device + self.model.train() + self.model = self.model.to(self.device) + + # Return metrics + return aggregate_metrics + + def _log(self, loss, metrics, grad_norm, step): + """Log to MLflow. + + Parameters + ---------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + grad_norm : float + Gradient norm + """ + + if not frequency_check(step, self.cfg.training.log_every_n_steps): + return + + metrics["loss"] = loss.item() + metrics["grad_norm"] = grad_norm + metrics["step"] = step + assert self._training_start_time is not None + metrics["time_total_s"] = time.time() - self._training_start_time + metrics["time_per_step_s"] = (time.time() - self._training_start_time) / (step + 1) + + for key, values in metrics.items(): + log_mlflow(f"train.{key}", values, step=step) + + def _load_dataset(self, tag): + """Loads dataset. To be implemented by subclasses. + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + raise NotImplementedError + + def _forward(self, *data): + """Model forward pass. To be implemented by subclasses. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + raise NotImplementedError + + def visualize(self, dataset, step): + """Visualization function. + + To be implemented by subclasses. + """ + + @property + def _eval_dataset_tags(self): + """Eval dataset tags, to be implemented by subclasses. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + return {"eval"} diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/base_wrapper.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/base_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..b78af1f4c16a4ed43a0508c9c9f5ad70e65138f0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/base_wrapper.py @@ -0,0 +1,142 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import nn + + +class BaseWrapper(nn.Module): + """Base GATr wrapper. + + To be subclassed by experiment-specific wrapper classes. + + Parameters + ---------- + net : torch.nn.Module + GATr network. + scalars : bool + Whether the GATr model uses auxiliary scalars in its inputs and outputs. (In hidden + representations, GATr uses auxiliary scalars always.) + return_other : bool + Whether the wrapper should return regularization terms in addition to the model predictions. + """ + + def __init__(self, net, scalars=True, return_other=True): + super().__init__() + self.net = net + self.scalars = scalars + self.return_other = return_other + + def build_attention_mask( + self, inputs, mv=None, s=None + ): # pylint: disable=unused-argument,redundant-returns-doc + """Construct attention mask. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs to wrapped network. + mv : torch.Tensor + Multivector embedding of inputs. + s : torch.Tensor + Auxiliary scalar embedding of inputs. + + Returns + ------- + attention_mask : None or torch.Tensor or xformers.ops.fmha.BlockDiagonalMask + Attention mask. + """ + return None + + def forward(self, inputs: torch.Tensor): + """Wrapped forward pass pass. + + Parses inputs into GA + scalar representation, calls the forward pass of the wrapped net, + and extracts the outputs from the GA + scalar representation again. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. Only returned if + `self.return_other`. + """ + + multivector, scalars = self.embed_into_ga(inputs) + mask = self.build_attention_mask( # pylint: disable=assignment-from-none + inputs, mv=multivector, s=scalars + ) + multivector_outputs, scalar_outputs = self.net( + multivector, scalars=scalars, attention_mask=mask + ) + outputs, other = self.extract_from_ga(multivector_outputs, scalar_outputs) + outputs = self.postprocess_results(inputs, outputs) + + if self.return_other: + return outputs, other + + return outputs + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + raise NotImplementedError + + def extract_from_ga(self, multivector, scalars): + """Extracts raw outputs from the GATr multivector + scalar outputs. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from GATr. + scalars : torch.Tensor or None + Scalar outputs from GATr. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + raise NotImplementedError + + def postprocess_results(self, inputs, outputs): # pylint: disable=unused-argument + """Postprocesses the outputs extracted from the GA representation. + + To be implemented by subclasses, optionally (by default, no postprocessing is applied). + + Parameters + ---------- + inputs + Raw inputs, pre embedding. + outputs : torch.Tensor + Raw outputs, pre postprocessing. + + Returns + ------- + processed_outputs : torch.Tensor + Raw outputs, after postprocessing. + """ + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05420100f17fb51777fef5d63baf69df607dcd14 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .dataset import NBodyDataset +from .experiment import NBodyExperiment +from .simulator import NBodySimulator +from .wrappers import ( + NBodyBaselineWrapper, + NBodyGATrWrapper, + NBodySE3TransformerWrapper, + NBodySEGNNWrapper, +) diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/dataset.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..117e97b5495572a1d967d207f98753f46c4bd425 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/dataset.py @@ -0,0 +1,76 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +import torch + + +class NBodyDataset(torch.utils.data.Dataset): + """N-body prediction dataset. + + Loads data generated with generate_nbody_dataset.py from disk. + + Parameters + ---------- + filename : str or pathlib.Path + Path to the npz file with the dataset to be loaded. + subsample : None or float + If not None, defines the fraction of the dataset to be used. For instance, `subsample=0.1` + uses just 10% of the samples in the dataset. + keep_trajectories : bool + Whether to keep the full particle trajectories in the dataset. They are neither needed + for training nor evaluation, but can be useful for visualization. + """ + + def __init__(self, filename, subsample=None, keep_trajectories=False): + super().__init__() + self.x, self.y, self.trajectories = self._load_data( + filename, subsample, keep_trajectories=keep_trajectories + ) + + def __len__(self): + """Returns the number of samples in the dataset.""" + return len(self.x) + + def __getitem__(self, idx): + """Returns the `idx`-th sample from the dataset.""" + return self.x[idx], self.y[idx] + + @staticmethod + def _load_data(filename, subsample=None, keep_trajectories=False): + """Loads data from file and converts to input and output tensors.""" + # Load data from file + npz = np.load(filename, "r") + m, x_initial, v_initial, x_final = ( + npz["m"], + npz["x_initial"], + npz["v_initial"], + npz["x_final"], + ) + + # Convert to tensors + m = torch.from_numpy(m).to(torch.float32).unsqueeze(2) + x_initial = torch.from_numpy(x_initial).to(torch.float32) + v_initial = torch.from_numpy(v_initial).to(torch.float32) + x_final = torch.from_numpy(x_final).to(torch.float32) + + # Concatenate into inputs and outputs + x = torch.cat((m, x_initial, v_initial), dim=2) # (batchsize, num_objects, 7) + y = x_final # (batchsize, num_objects, 3) + + # Optionally, keep raw trajectories around (for plotting) + if keep_trajectories: + trajectories = npz["trajectories"] + else: + trajectories = None + + # Subsample + if subsample is not None and subsample < 1.0: + n_original = len(x) + n_keep = int(round(subsample * n_original)) + assert 0 < n_keep <= n_original + x = x[:n_keep] + y = y[:n_keep] + if trajectories is not None: + trajectories = trajectories[:n_keep] + + return x, y, trajectories diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/experiment.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c746f9fa80cf26d2da99399703e48ab3bf8a0f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/experiment.py @@ -0,0 +1,99 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from pathlib import Path + +import torch + +from gatr.experiments.base_experiment import BaseExperiment +from gatr.experiments.nbody.dataset import NBodyDataset + + +class NBodyExperiment(BaseExperiment): + """Experiment manager for n-body prediction. + + Parameters + ---------- + cfg : OmegaConf + Experiment configuration. See the config folder in the repository for examples. + """ + + def __init__(self, cfg): + super().__init__(cfg) + self._mse_criterion = torch.nn.MSELoss() + self._mae_criterion = torch.nn.L1Loss(reduction="mean") + + def _load_dataset(self, tag): + """Loads dataset. + + Parameters + ---------- + tag : str + Dataset tag, like "train", "val", or one of self._eval_tags. + + Returns + ------- + dataset : torch.utils.data.Dataset + Dataset. + """ + + if tag == "train": + subsample_fraction = self.cfg.data.subsample + else: + subsample_fraction = None + + filename = Path(self.cfg.data.data_dir) / f"{tag}.npz" + keep_trajectories = tag == "val" + return NBodyDataset( + filename, subsample=subsample_fraction, keep_trajectories=keep_trajectories + ) + + def _forward(self, *data): + """Model forward pass. + + Parameters + ---------- + data : tuple of torch.Tensor + Data batch. + + Returns + ------- + loss : torch.Tensor + Loss + metrics : dict with str keys and float values + Additional metrics for logging + """ + + # Forward pass + assert self.model is not None + x, y = data + y_pred, reg = self.model(x) + + # Compute loss + mse = self._mse_criterion(y_pred, y) + output_reg = torch.mean(reg) + loss = mse + self.cfg.training.output_regularization * output_reg + + # Additional metrics + mae = self._mae_criterion(y_pred, y) + metrics = dict( + mse=mse.item(), rmse=loss.item() ** 0.5, output_reg=output_reg.item(), mae=mae.item() + ) + + return loss, metrics + + @property + def _eval_dataset_tags(self): + """Eval dataset tags. + + Returns + ------- + tags : iterable of str + Eval dataset tags + """ + + # Only evaluate on object_generalization dataset when method supports variable token number + assert self.model is not None + if self.model.supports_variable_items: + return {"eval", "e3_generalization", "object_generalization"} + + return {"eval", "e3_generalization"} diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/simulator.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ffedae9f88bfb94cd20473c37aa791bd8bb649 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/simulator.py @@ -0,0 +1,223 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +from scipy.stats import special_ortho_group + +from gatr.utils.misc import sample_log_uniform, sample_uniform_in_circle + + +class NBodySimulator: + """Simulator for the n-body dataset. + + Each sample consists of the positions of a n particicles (1 star and n - 1 planets), both before + and after the evolution of 100 time steps. The particle masses are also part of the sample. + + The data is generated in the following way: + 1. The masses for the star and planets are sampled. + 2. The initial planet positions are sampled around the origin in the x-y plane. The star is at + (0, 0). + 3. The initial planet velocities are given by the velocity of a stable circular orbit, plus some + noise. + The star is initially at rest. + 4. The initial state is translated and rotated to an arbitrary position and orientation in + space. + 5. The final state is computed (using Newton's equations of gravity and Newton's method). + 6. To avoid annoying outliers, samples where the initial and final position of any object + are more than outlier_threshold are removed. + + We use units where G = 1. + + Parameters + ---------- + time : float + Overall time period between initial and final state. + time_steps : int + Number of time steps that the time window is divided into for Euler integration. + star_mass_range : tuple of float + Minimum and maximum mass for the star. + planet_mass_range : tuple of float + Minimum and maximum mass for the planets. + radius_range : tuple of float + Minimum and maximum initial distance of the planets from the star. + vel_std : float + Noise scale for the initial planet velocity. + shift_std : float + Noise scale for the spatial translation. + ood_shift : float + Noise scale for the spatial translation for the translated sample. + outlier_threshold : float + Threshold for the rejection of outlier samples in which initial and final positions differ + substantially. + """ + + def __init__( + self, + time=0.1, + time_steps=100, + star_mass_range=(1.0, 10.0), + planet_mass_range=(0.01, 0.1), + radius_range=(0.1, 1.0), + vel_std=0.01, + shift_std=20.0, + ood_shift=200.0, + outlier_threshold=2.0, + ): + self.time = time + self.delta_t = time / time_steps + self.time_steps = time_steps + self.star_mass_range = star_mass_range + self.planet_mass_range = planet_mass_range + self.radius_range = radius_range + self.vel_std = vel_std + self.shift_std = shift_std + self.ood_shift = ood_shift + self.outlier_threshold = outlier_threshold + + def sample(self, num_samples, num_planets=5, domain_shift=False): + """Samples from gravity problem. + + Parameters + ---------- + num_samples : int + Number of samples. + num_planets : int + Number of planets in the dataset (as there is always a single star, we have + `n = num_planets + 1`). + domain_shift : bool + Whether to sample with larger spatial translation to generate domain-shifted data. + """ + + # Sample a bit more initially, to make up for outlier removal later + num_candidates = int(round(1.1 * num_samples)) + + # 1. Sample planet masses + star_mass = sample_log_uniform(*self.star_mass_range, size=(num_candidates, 1)) + planet_masses = sample_log_uniform( + *self.planet_mass_range, size=(num_candidates, num_planets) + ) + masses = np.concatenate((star_mass, planet_masses), axis=1) + + # 2. Sample initial positions in x-y plane around origin + planet_pos = np.zeros((num_candidates, num_planets, 3)) + planet_pos[..., :2] = sample_uniform_in_circle( + num_candidates * num_planets, + min_radius=self.radius_range[0], + max_radius=self.radius_range[1], + ).reshape((num_candidates, num_planets, 2)) + x_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_pos), axis=1) + + # 3. Sample initial velocities, approximately as stable circular orbits + planet_vel = self._sample_planet_velocities(star_mass, planet_pos) + v_initial = np.concatenate((np.zeros((num_candidates, 1, 3)), planet_vel), axis=1) + + # 4. Translate, rotate, permute + masses, x_initial, v_initial = self._shift_and_rotate( + masses, x_initial, v_initial, domain_shift=domain_shift + ) + + # 5. Evolve Newtonian gravity + x_final, trajectory = self._simulate(masses, x_initial, v_initial) + + # 6. Remove outliers + max_distance = np.max(np.linalg.norm(x_final - x_initial, axis=-1), axis=-1) + mask = max_distance <= self.outlier_threshold + masses, x_initial, v_initial, x_final, trajectory = ( + masses[mask], + x_initial[mask], + v_initial[mask], + x_final[mask], + trajectory[mask], + ) + + # Cut down to requested number + masses, x_initial, v_initial, x_final, trajectory = ( + masses[:num_samples], + x_initial[:num_samples], + v_initial[:num_samples], + x_final[:num_samples], + trajectory[:num_samples], + ) + + return masses, x_initial, v_initial, x_final, trajectory + + def _sample_planet_velocities(self, star_mass, x): + """Samples planet velocities around those that give stable circular orbits.""" + + batchsize, num_planets, _ = x.shape + + # Defines rotation plane. Clockwise or counterclockwise is random for each planet. + orientation = np.zeros((batchsize, num_planets, 3)) + orientation[:, :, 2] = np.random.choice( + a=[-1.0, 1.0], size=(batchsize, num_planets), p=[0.5, 0.5] + ) + + # Compute stable velocities + star_mass = star_mass[:, :, np.newaxis] # (batchsize, 1, 1) + radii = np.linalg.norm(x, axis=-1)[:, :, np.newaxis] # (batchsize, num_planets, 1) + v_stable = np.cross(orientation, x) * star_mass**0.5 / radii**1.5 + + # Add noise + v = v_stable + np.random.normal(scale=self.vel_std, size=(batchsize, num_planets, 3)) + + return v + + def _shift_and_rotate(self, m, x, v, domain_shift=False): + """Performs random E(3) transformations and permutations on given positions / velocities.""" + + batchsize, num_objects, _ = x.shape + + # Permutations over objects + for i in range(batchsize): + perm = np.random.permutation(num_objects) + m[i] = m[i][perm] + x[i] = x[i][perm, :] + v[i] = v[i][perm, :] + + # Rotations from Haar measure + rotations = special_ortho_group(3).rvs(size=batchsize).reshape(batchsize, 1, 3, 3) + x = np.einsum("bnij,bnj->bni", rotations, x) + v = np.einsum("bnij,bnj->bni", rotations, v) + + # Translations + shifts = np.random.normal(scale=self.shift_std, size=(batchsize, 1, 3)) + x = x + shifts + + # OOD shift + if domain_shift: + shifts = np.array([self.ood_shift, 0, 0]).reshape((1, 1, 3)) + x = x + shifts + + return m, x, v + + def _simulate(self, m, x_initial, v_initial): + """Evolves an initial state under Newtonian equations of motions.""" + + x, v = x_initial, v_initial + trajectory = [x_initial] + + for _ in range(self.time_steps): + a = self._compute_accelerations(m, x) + v = v + self.delta_t * a + x = x + self.delta_t * v + trajectory.append(x) + + return x, np.array(trajectory).transpose([1, 2, 0, 3]) + + @staticmethod + def _compute_accelerations(m, x): + """Computes accelerations for a set of point masses according to Newtonian gravity.""" + batchsize, num_objects, _ = x.shape + mm = m.reshape((batchsize, 1, num_objects, 1)) * m.reshape( + (batchsize, num_objects, 1, 1) + ) # (b, n, n, 1) + + distance_vectors = x.reshape((batchsize, 1, num_objects, 3)) - x.reshape( + (batchsize, num_objects, 1, 3) + ) # (b, n, n, 3) + distances = np.linalg.norm(distance_vectors, axis=-1)[:, :, :, np.newaxis] # (b, n, n, 1) + distances[np.abs(distances) < 1e-9] = 1.0 + + forces = distance_vectors * mm / distances**3 # (b, n, n, 3) + accelerations = np.sum(forces, axis=2) / m.reshape(batchsize, num_objects, 1) # (b, n, 3) + + return accelerations # (b, n, 3) diff --git a/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/wrappers.py b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0693a8baa3763815fff4bda4eb54ece1f5a578 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/experiments/nbody/wrappers.py @@ -0,0 +1,489 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import dgl +import numpy as np +import torch +from e3nn.o3 import Irreps, spherical_harmonics +from torch import nn +from torch_geometric.data import Data +from torch_geometric.nn import knn_graph +from torch_scatter import scatter + +from gatr.baselines.gcan import GCAGNN +from gatr.baselines.transformer import BaselineAxialTransformer, BaselineTransformer +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import ( + embed_point, + embed_scalar, + embed_translation, + extract_point, + extract_point_embedding_reg, +) +from gatr.utils.misc import make_full_edge_index + + +def embed_nbody_data_in_pga(inputs): + """Represent the n-body initial state in PGA multivectors. + + Masses are represented as scalars, positions as trivectors, and velocities as bivectors + (like translations). All three are summed (this is equivalent to concatenation, as an equi + linear layer can easily separate the grades again). + + This function is used both by the GATr and by the GCAN wrappers. + + Parameters + ---------- + inputs : torch.Tensor with shape (batchsize, objects, 7) + n-body initial state: a concatenation of masses, initial positions, and initial + velocities along the feature dimension. + + Returns + ------- + multivector : torch.Tensor with shape (batchsize, objects, 1, 16) + GA embedding. + """ + + # Build one multivector holding masses, points, and velocities for each object + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + masses = embed_scalar(masses) # (batchsize, objects, 16) + points = inputs[:, :, 1:4] # (batchsize, objects, 3) + points = embed_point(points) # (batchsize, objects, 16) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + velocities = embed_translation(velocities) # (batchsize, objects, 16) + multivector = masses + points + velocities # (batchsize, objects, 16) + + # Insert channel dimension + multivector = multivector.unsqueeze(2) # (batchsize, objects, 1, 16) + + return multivector + + +class NBodyGATrWrapper(BaseWrapper): + """Wraps around GATr for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + GATr model that accepts inputs with 1 multivector channel and 1 scalar channel, and + returns outputs with 1 multivector channel and 1 scalar channel. + """ + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=True) + self.supports_variable_items = True + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + Parameters + ---------- + inputs : torch.Tensor with shape (batchsize, objects, 7) + n-body initial state: a concatenation of masses, initial positions, and initial + velocities along the feature dimension. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector representation of masses, positions, and velocities. + scalar_inputs : torch.Tensor or None + Dummy auxiliary scalars, containing no information. + """ + batchsize, num_objects, _ = inputs.shape + + # Build one multivector holding masses, positions, and velocities for each object + multivector = embed_nbody_data_in_pga(inputs) + + # Scalar inputs are not really needed here + scalars = torch.zeros((batchsize, num_objects, 1), device=inputs.device) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Extracts raw outputs from the GATr multivector + scalar outputs. + + We parameterize the predicted final positions as points. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from GATr. + scalars : torch.Tensor or None + Scalar outputs from GATr. + + Returns + ------- + outputs : torch.Tensor + Predicted final-state positions. + other : torch.Tensor + Regularization terms. + """ + + # Check channels of inputs. Batchsize and object numbers are free. + assert multivector.shape[2:] == (1, 16) + assert scalars.shape[2:] == (1,) + + # Extract position + points = extract_point(multivector[:, :, 0, :]) + + # Extract non-point components and compute regularization + other = extract_point_embedding_reg(multivector[:, :, 0, :]) + reg = torch.sum(other**2, dim=[1, 2]) + if self.scalars: + reg = reg + torch.sum(scalars**2, dim=[1, 2]) + + return points, reg + + +class NBodyBaselineWrapper(nn.Module): + """Wraps around simple baselines (MLP or Transformer) for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + Model that accepts inputs with 7 channels and returns outputs with 3 channels. + """ + + def __init__(self, net): + super().__init__() + self.net = net + self.supports_variable_items = isinstance( + net, (BaselineTransformer, BaselineAxialTransformer) + ) + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + """ + batchsize = inputs.shape[0] + return self.net(inputs), torch.zeros(batchsize, device=inputs.device) + + +class NBodySEGNNWrapper(nn.Module): + """Wraps around the SEGNN baseline for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + SEGNN model that accepts inputs with inputs with 2 vector channels and 1 scalar channel, + and returns outputs with 1 vector channel. + """ + + def __init__(self, net, neighbors, lmax_attr, canonicalize_mode="com"): + super().__init__() + + self.net = net + + self.canonicalize_mode = canonicalize_mode + self.neighbors = neighbors + self.transform_attr_irreps = Irreps.spherical_harmonics(lmax_attr) + self.supports_variable_items = True + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + + Raises + ------ + ValueError + If `self.canonicalize_mode` is invalid. + """ + batchsize, num_objects, _ = inputs.shape + + # Separate into scalars and vectors + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + locations = inputs[:, :, 1:4] # (batchsize, objects, 3) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + + # Canonicalize + if self.canonicalize_mode == "com": + weights = masses + elif self.canonicalize_mode == "heaviest": + weights = torch.exp(2.0 * masses.double()) + elif self.canonicalize_mode == "even": + weights = torch.ones_like(masses) + else: + raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}") + + com = torch.sum( + weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(), + dim=-2, + keepdim=True, + ).float() + locations = locations - com + + # Represent as graph + graph = Data(pos=locations.view(-1, 3), vel=velocities.view(-1, 3), mass=masses.view(-1, 1)) + batch = torch.arange(0, batchsize, device=inputs.device) + graph.batch = batch.repeat_interleave(num_objects).to(inputs.device, torch.long) + graph.edge_index = knn_graph(locations.view(-1, 3), self.neighbors, graph.batch) + + graph = self._augment_gravity_graph(graph) # Add O3 attributes + + # Push through model + pred_shift = self.net(graph) + pred_shift = pred_shift.view(batchsize, num_objects, 3) + predictions = ( + locations + pred_shift + ) # The model predicts the shift, not the final positions + + # Undo canonicalization + predictions = predictions + com + + return predictions, torch.zeros(batchsize, device=inputs.device) + + def _augment_gravity_graph(self, graph): + """SEGNN feature engineering for n-body experiments. + + Constructs node features (position relative to mean position, velocity embedding, absolute + velocity) and edge features (pairwise distances, product of charges / masses). + """ + + pos = graph.pos + vel = graph.vel + mass = graph.mass + + prod_mass = mass[graph.edge_index[0]] * mass[graph.edge_index[1]] + rel_pos = pos[graph.edge_index[0]] - pos[graph.edge_index[1]] + edge_dist = torch.sqrt(rel_pos.pow(2).sum(1, keepdims=True)) + + graph.edge_attr = spherical_harmonics( + self.transform_attr_irreps, rel_pos, normalize=True, normalization="integral" + ) + vel_embedding = spherical_harmonics( + self.transform_attr_irreps, vel, normalize=True, normalization="integral" + ) + graph.node_attr = ( + scatter(graph.edge_attr, graph.edge_index[1], dim=0, reduce="mean") + vel_embedding + ) + + vel_abs = torch.sqrt(vel.pow(2).sum(1, keepdims=True)) + + graph.x = torch.cat((pos, vel, vel_abs), 1) # Note that pos is here already canonicalized + graph.additional_message_features = torch.cat((edge_dist, prod_mass), dim=-1) + return graph + + +class NBodySE3TransformerWrapper(nn.Module): + """Wraps around the SE3-Transformer baseline for the n-body prediction experiment. + + Parameters + ---------- + net : torch.nn.Module + SE3-Transformer model. + """ + + def __init__(self, net, canonicalize_to_com=True, canonicalize_mode="com"): + super().__init__() + + self.net = net + self.canonicalize_to_com = canonicalize_to_com + self.canonicalize_mode = canonicalize_mode + self.supports_variable_items = True + + def forward(self, inputs): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + + Raises + ------ + ValueError + If `self.canonicalize_mode` is invalid. + """ + batchsize, num_objects, _ = inputs.shape + + # Separate into scalars and vectors + masses = inputs[:, :, [0]] # (batchsize, objects, 1) + locations = inputs[:, :, 1:4] # (batchsize, objects, 3) + velocities = inputs[:, :, 4:7] # (batchsize, objects, 3) + + # Canonicalize to center-of-mass frame if requested + if self.canonicalize_to_com: + if self.canonicalize_mode == "com": + weights = masses + elif self.canonicalize_mode == "heaviest": + weights = torch.exp(2.0 * masses.double()) + else: + raise ValueError(f"Unknown canonicalization mode {self.canonicalize_mode}") + com = torch.sum( + weights / torch.sum(weights, dim=-2, keepdim=True) * locations.double(), + dim=-2, + keepdim=True, + ).float() + locations = locations - com + else: + com = torch.zeros_like(locations) + + # Represent as graph + graphs = self._build_graphs(locations, velocities, masses) + + # Push through model + predictions = self.net(graphs) + predictions = predictions[:, 0, :] # Only positions, not velocities + predictions = predictions.view(batchsize, num_objects, 3) + predictions = ( + locations + predictions + ) # Model predicts positions relative to initial pos, make it absolute + + # Undo canonicalization + if self.canonicalize_to_com: + predictions = predictions + com + + return predictions, torch.zeros(batchsize, device=inputs.device) + + def _build_graphs(self, locations, velocities, masses): + """Builds graph for a full batch.""" + graphs = [ + self._build_graph(loc, vel, m) for loc, vel, m in zip(locations, velocities, masses) + ] + graphs = dgl.batch(graphs) + + return graphs + + def _build_graph(self, locations, velocities, masses): + """Builds graph for a single sample.""" + n_points = len(locations) + indices_src, indices_dst = self._fully_connected_idx(n_points) + graph = dgl.DGLGraph((indices_src, indices_dst)).to(locations.device) + graph.ndata["x"] = torch.unsqueeze(locations, dim=1) # [N, 1, 3] + graph.ndata["v"] = torch.unsqueeze(velocities, dim=1) # [N, 1, 3] + graph.ndata["c"] = torch.unsqueeze(masses, dim=1) # [N, 1, 1] + graph.edata["d"] = locations[indices_dst] - locations[indices_src] # relative postions + graph.edata["w"] = masses[indices_dst] * masses[indices_src] + return graph + + @staticmethod + def _fully_connected_idx(num_atoms): + """Creates source and destination indices for a fully connected graph.""" + src = [] + dst = [] + for i in range(num_atoms): + for j in range(num_atoms): + if i != j: + src.append(i) + dst.append(j) + return np.array(src), np.array(dst) + + +class NBodyGCANWrapper(nn.Module): + """Wraps around GCA-MLP and GCA-GNN baselines for the n-body experiment. + + Parameters + ---------- + net : torch.nn.Module + GCAN model that accepts inputs with multivector inputs with 1 channel and + returns multivector outputs with 1 channel. + """ + + def __init__(self, net, geometric_batching=False): + super().__init__() + self.net = net + self._geometric_batching = geometric_batching + self.supports_variable_items = isinstance(net, GCAGNN) + + def forward(self, inputs: torch.Tensor): + """Wrapped forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Dummy term, since the baselines do not require regularization. + """ + + multivector = embed_nbody_data_in_pga(inputs) + + if self._geometric_batching: + # PyG-style batching, with a single batch-token dimension and edge list + edge_index = self.make_edge_index(inputs) + multivector = multivector.view(-1, *multivector.shape[2:]) + multivector_outputs = self.net(multivector, edge_index=edge_index) + multivector_outputs = multivector_outputs.view( + inputs.shape[0], -1, *multivector_outputs.shape[1:] + ) + else: + # Standard batching, with (batch, token, ...) tensors + multivector_outputs = self.net(multivector) + + outputs, reg = self.extract_from_ga(multivector_outputs) + return outputs, reg + + @staticmethod + def extract_from_ga(multivector): + """Extracts predicted positions from PGA multivectors.""" + # Check channels of inputs. Batchsize and object numbers are free. + assert multivector.shape[2:] == (1, 16) + + # Extract position + points = extract_point(multivector[:, :, 0, :]) + + # Extract non-point components and compute regularization + other = extract_point_embedding_reg(multivector[:, :, 0, :]) + reg = torch.sum(other**2, dim=[1, 2]) + return points, reg + + @staticmethod + def make_edge_index(inputs): + """Constructs an edge index for fully connected graph.""" + batchsize, num_items, _ = inputs.shape + return make_full_edge_index( + num_items, batchsize=batchsize, self_loops=False, device=inputs.device + ) + + def to(self, *args, **kwargs): + """Send to device. + + Overwritten to also move the CliffordAlgebra object, which is not an nn.Module. + """ + resursively_move_gcan_pga(self, *args, **kwargs) + super().to(*args, **kwargs) + return self + + +def resursively_move_gcan_pga(net, *args, **kwargs): + """Moves all PGA instances in GCAN component to device / dtype.""" + try: + net.pga.to(*args, **kwargs) + except AttributeError: + pass + + for child in net.children(): + resursively_move_gcan_pga(child, *args, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d358aaf1fc027eea4f16fdbb39d8de030afd5d75 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .object import ( + embed_3d_object, + embed_3d_object_two_vec, + extract_3d_object, + extract_3d_object_two_vec, +) +from .plane import embed_oriented_plane, extract_oriented_plane +from .point import embed_point, extract_point, extract_point_embedding_reg +from .pseudoscalar import embed_pseudoscalar, extract_pseudoscalar +from .reflection import embed_reflection, extract_reflection +from .rotation import embed_rotation, extract_rotation +from .scalar import embed_scalar, extract_scalar +from .translation import embed_translation, extract_translation diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/object.py b/gafl/build/geometric-algebra-transformer/gatr/interface/object.py new file mode 100644 index 0000000000000000000000000000000000000000..faa706ee5f18e93815c3ec1281fe891dd137074c --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/object.py @@ -0,0 +1,212 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Optional + +import torch + +from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane +from gatr.interface.point import embed_point, extract_point +from gatr.interface.rotation import embed_rotation, extract_rotation +from gatr.interface.translation import embed_translation +from gatr.primitives.bilinear import geometric_product, outer_product +from gatr.primitives.linear import reverse + + +def embed_3d_object( + position: torch.Tensor, orientation: torch.Tensor, explicit_point: bool = False +) -> torch.Tensor: + """Embeds the pose of a 3D object PGA multivectors. + + The pose is given by a position and a orientation quaternion. The latter is assumed to follow + the pybullet conventions: to be given in Hamilton convention, where ijk = -1, and with the + scalar component last (ijkw order). + + The embedding contains three plane multivectors v_i with + ``` + v_i = T(p) R(q) e_i reverse(T(p) R(q)) + ``` + where `T()` is the translation embedding, `R()` is the rotation embedding, and `e_i` are the PGA + basis vectors. + + If `explicit_point`, then a fourth multivector represents the position itself. + + References + ---------- + Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478 + + Parameters + ---------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1) + explicit_point : bool + If True, in addition to the three planes we provide the explicit point representation + `P(p)`. + + Returns + ------- + multivector : torch.Tensor with shape (..., n_channels, 16) + Embedding into multivectors, with `n_channels = 4 if explicit_point else 3`. + """ + + # Check inputs + assert position.shape[-2:] == (1, 3) + assert orientation.shape[-2:] == (1, 4) + + # Basis planes + basis = torch.zeros(3, 16, dtype=position.dtype, device=position.device) # (3, 16) + basis[:, 2:5] = torch.eye( + 3, dtype=position.dtype, device=position.device + ) # basis[i] has e_i = 1 + + # Translation and rotation + t = embed_translation(position) # (..., 1, 16) + r = embed_rotation(orientation) # (..., 1, 16) + tr = geometric_product(t, r) # (..., 1, 16) + + # Construct embedding + embedding = geometric_product(geometric_product(tr, basis), reverse(tr)) # (..., 3, 16) + + # Optional point embedding + if explicit_point: + point = embed_point(position) + embedding = torch.cat((embedding, point), dim=-2) # (..., 4, 16) + + return embedding + + +def extract_3d_object( + multivector: torch.Tensor, + normalize_quaternion: bool = True, + sign_reference: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """Extracts 3D position and quaternion orientation from the multivector embedding of an object. + + This function inverts embed_3d_object(). + + The extraction starts from three (plane) MVs v_i and is based on the magic equation + ``` + P(p) = v_1 ^ v_2 ^ v_3 + q = (1 + sum_i _E e_i) + ``` + where `_E` is the projection of v_i to the Euclidean vector components. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 3 or 4, 16) + Object embedding. + normalize_quaternion : bool + Whether to normalize quaternions. + sign_reference : None or torch.Tensor + If provided, used to fix the (ambiguous) sign of the orientation quaternion. + + Returns + ------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1). + """ + + # Split inputs + v = [multivector[..., [i], :] for i in range(3)] # (..., 1, 16) each + + # Basis vectors + basis = torch.zeros(3, 16, dtype=multivector.dtype, device=multivector.device) # (3, 16) + basis[:, 2:5] = torch.eye( + 3, dtype=multivector.dtype, device=multivector.device + ) # basis[i] has e_i = 1 + projection = torch.sum(basis, dim=0) # (16) + + # Extract position + if multivector.shape[-2] == 4: + position = extract_point(multivector[..., [3], :]) # (..., 1, 3) + else: + position = outer_product(outer_product(v[0], v[1]), v[2]) # (..., 1, 16) + position = extract_point(position) # (..., 1, 3) + + # Extract orientation + orientation = torch.zeros(16, dtype=multivector.dtype, device=multivector.device) + orientation[0] = 1.0 + for vi, ei in zip(v, basis): + vi_proj = projection * vi # Project to Euclidean vector components + orientation = orientation + geometric_product(vi_proj, ei) # Magic equation + + quat = extract_rotation(orientation, normalize=normalize_quaternion) + + # Fix quaternion sign + if sign_reference is not None: + sign = torch.sign(torch.sum(sign_reference * quat, dim=-1, keepdim=True)) + quat = sign * quat + + return position, quat + + +def embed_3d_object_two_vec(position: torch.Tensor, orientation: torch.Tensor) -> torch.Tensor: + """Embeds the pose of a 3D object in two-vec parameterization into the PGA. + + The inputs consist of the position of an object and two vectors that specify its orientation. + These two vectors can be generated from a rotation matrix by taking the first two column + vectors. + + The embedding contains three planes and a point, just like embed_3d_object(). + + Parameters + ---------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 6) + Orientation in two-vec parameterization + + Returns + ------- + multivector : torch.Tensor with shape (..., 4, 16) + Embedding into three multivectors. + """ + + # Check inputs + assert position.shape[-2:] == (1, 3) + assert orientation.shape[-2:] == (1, 6) + + # Point + point_embedding = embed_point(position) # (..., 1, 16) + + # Two-vec -> three vectors + orientation = orientation.reshape(*orientation.shape[:-2], 2, 3) + third_vec = torch.linalg.cross(orientation[..., [0], :], orientation[..., [1], :]) + orientation = torch.cat((orientation, third_vec), dim=-2) + + # Embed orientation as planes + orientation_embedding = embed_oriented_plane(orientation, position) # (..., 3, 16) + + embedding = torch.cat((point_embedding, orientation_embedding), dim=-2) # (..., 4, 16) + return embedding + + +def extract_3d_object_two_vec(multivector: torch.Tensor) -> torch.Tensor: + """Extracts 3D position and two-vec orientation from the multivector embedding of an object. + + This inverts embed_3d_object_two_vec(). + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 3, 16) + Object embedding. + + Returns + ------- + position : torch.Tensor with shape (..., 1, 3) + Position in 3D space. + orientation : torch.Tensor with shape (..., 1, 6) + Two-vec param of orientation + """ + + # Position + position = extract_point(multivector[..., [0], :]) # (..., 1, 3) + + # Orientation + orientation = extract_oriented_plane(multivector[..., [1, 2], :]) # (..., 2, 3) + orientation = orientation.reshape(*multivector.shape[:-2], 1, 6) # (..., 1, 6) + + return position, orientation diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/plane.py b/gafl/build/geometric-algebra-transformer/gatr/interface/plane.py new file mode 100644 index 0000000000000000000000000000000000000000..4036bebcf09c5a5ddbe21b70164d4391935235b2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/plane.py @@ -0,0 +1,72 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from torch import Tensor + +from gatr.interface.translation import embed_translation +from gatr.primitives.bilinear import geometric_product + + +def embed_oriented_plane(normal: Tensor, position: Tensor) -> Tensor: + """Embeds an (oriented plane) in the PGA. + + Following L. Dorst, the plane is represent as PGA vectors. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + position : torch.Tensor with shape (..., 3) + One position on the plane. + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = normal.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=normal.dtype, device=normal.device) + + # Embedding a plane through origin into vectors + multivector[..., 2:5] = normal[..., :] + + # Shift away from origin by translating + translation = embed_translation(position) + inverse_translation = embed_translation(-position) + multivector = geometric_product( + geometric_product(translation, multivector), inverse_translation + ) + + return multivector + + +def extract_oriented_plane(multivector: torch.Tensor) -> torch.Tensor: + """Extracts the normal on an oriented plane from a multivector. + + Currently, this function does *not* extract a support point for the plane (or the distance to + the origin). + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + + Returns + ------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + """ + + return multivector[..., 2:5] diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/point.py b/gafl/build/geometric-algebra-transformer/gatr/interface/point.py new file mode 100644 index 0000000000000000000000000000000000000000..b350cfd100be736189d1949af1ae2bdfb83e27be --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/point.py @@ -0,0 +1,104 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Functions that embed points in the geometric algebra.""" + + +import torch + + +def embed_point(coordinates: torch.Tensor) -> torch.Tensor: + """Embeds 3D points in multivectors. + + We follow the convention used in the reference below and map points to tri-vectors. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + coordinates : torch.Tensor with shape (..., 3) + 3D coordinates + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = coordinates.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=coordinates.dtype, device=coordinates.device) + + # Embedding into trivectors + # Homogeneous coordinates: unphysical component / embedding dim, x_123 + multivector[..., 14] = 1.0 + multivector[..., 13] = -coordinates[..., 0] # x-coordinate embedded in x_023 + multivector[..., 12] = coordinates[..., 1] # y-coordinate embedded in x_013 + multivector[..., 11] = -coordinates[..., 2] # z-coordinate embedded in x_012 + + return multivector + + +def extract_point( + multivector: torch.Tensor, divide_by_embedding_dim: bool = True, threshold: float = 1e-3 +) -> torch.Tensor: + """Given a multivector, extract any potential 3D point from the trivector components. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + divide_by_embedding_dim : bool + Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it + may not be good for NN training. + threshold : float + Minimum value of the additional, unphysical component. Necessary to avoid exploding values + or NaNs when this unphysical component of the homogeneous coordinates becomes small. + + Returns + ------- + coordinates : torch.Tensor with shape (..., 3) + 3D coordinates corresponding to the trivector components of the multivector. + """ + + coordinates = torch.cat( + [-multivector[..., [13]], multivector[..., [12]], -multivector[..., [11]]], dim=-1 + ) + + # Divide by embedding dim + if divide_by_embedding_dim: + embedding_dim = multivector[ + ..., [14] + ] # Embedding dimension / scale of homogeneous coordinates + embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold) + coordinates = coordinates / embedding_dim + + return coordinates + + +def extract_point_embedding_reg(multivector: torch.Tensor) -> torch.Tensor: + """Given a multivector x, returns |x_{123}| - 1. + + Put differently, this is the deviation of the norm of a pseudoscalar component from 1. + This can be used as a regularization term when predicting point positions, to avoid x_123 to + be too close to 0. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + + Returns + ------- + regularization : torch.Tensor with shape (..., 1) + |multivector_123| - 1. + """ + + return torch.abs(multivector[..., [14]]) - 1.0 diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/pseudoscalar.py b/gafl/build/geometric-algebra-transformer/gatr/interface/pseudoscalar.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16ed0bfcdccb6f75f99040b12d956f982a7f17 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/pseudoscalar.py @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_pseudoscalar(pseudoscalars: torch.Tensor) -> torch.Tensor: + """Embeds a pseudoscalar tensor into multivectors. + + Parameters + ---------- + pseudoscalars: torch.Tensor with shape (..., 1) + Pseudoscalar inputs. + + Returns + ------- + multivectors: torch.Tensor with shape (..., 16) + Multivector outputs. `multivectors[..., [15]]` is the same as `pseudoscalars`. + The other components are zero. + """ + + non_scalar_shape = list(pseudoscalars.shape[:-1]) + [15] + non_scalar_components = torch.zeros( + non_scalar_shape, device=pseudoscalars.device, dtype=pseudoscalars.dtype + ) + embedding = torch.cat((non_scalar_components, pseudoscalars), dim=-1) + + return embedding + + +def extract_pseudoscalar(multivectors: torch.Tensor) -> torch.Tensor: + """Extracts pseudoscalar components from multivectors. + + Parameters + ---------- + multivectors: torch.Tensor with shape (..., 16) + Multivector inputs. + + Returns + ------- + pseudoscalars: torch.Tensor with shape (..., 1) + Pseudoscalar component of multivectors. + """ + + return multivectors[..., [15]] diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/reflection.py b/gafl/build/geometric-algebra-transformer/gatr/interface/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..926a478a4346c3f04bad52adbcddca3e042d87d2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/reflection.py @@ -0,0 +1,56 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Functions that create multivectors representing elements of the Pin group.""" + + +from torch import Tensor + +from gatr.interface.plane import embed_oriented_plane, extract_oriented_plane + + +def embed_reflection(normal: Tensor, position: Tensor) -> Tensor: + """Embeds the reflection on a plane in multivectors. + + Following L. Dorst, this is represented as a PGA vector. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + normal : Tensor with shape (..., 3) + Normal to the reflection plane. + position : Tensor with shape (..., 3) + One position on the reflection plane. + + Returns + ------- + multivector : Tensor with shape (..., 16) + Embedding into multivector. + """ + + return embed_oriented_plane(normal, position) + + +def extract_reflection(multivector: Tensor) -> Tensor: + """Extracts the normal on an reflection plane from a multivector. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + + Returns + ------- + normal : torch.Tensor with shape (..., 3) + Normal to the plane. + """ + + return extract_oriented_plane(multivector) diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/rotation.py b/gafl/build/geometric-algebra-transformer/gatr/interface/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..0dba94b83d8be06fddd15a5ccc354601974b4370 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/rotation.py @@ -0,0 +1,75 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_rotation(quaternion: torch.Tensor) -> torch.Tensor: + """Embeds 3D rotations in multivectors. + + We follow the convention used in Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra + PGA", and map rotations around the origin to bivectors. + + For quaternions we use the "Hamilton" convention, where ijk = -1 (*not* the JPL convention + where ijk = 1). For details, see "Why and How to Avoid the Flipped Quaternion Multiplication" + by Sommer et al. (2018) + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + Sommer et al., "Why and How to Avoid the Flipped Quaternion Multiplication", arXiv:1801.07478 + + Parameters + ---------- + quaternion : torch.Tensor with shape (..., 4) + Quaternions in ijkw order and Hamilton convention (ijk=-1) + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = quaternion.shape[:-1] + multivector = torch.zeros(*batch_shape, 16, dtype=quaternion.dtype, device=quaternion.device) + + # Embedding into bivectors + # w component of quaternion is the scalar component of the multivector + multivector[..., 0] = quaternion[..., 3] + multivector[..., 8] = -quaternion[..., 2] # k component of quaternion is the bivector -e12 + multivector[..., 9] = quaternion[..., 1] # j component of quaternion is the bivector e13 + multivector[..., 10] = -quaternion[..., 0] # i component of quaternion is the bivector -e23 + + return multivector + + +def extract_rotation(multivector: torch.Tensor, normalize: bool = False) -> torch.Tensor: + """Extracts the represented rotation quaternion from the multivector's bivector components. + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + normalize : bool + Whether to normalize the quaternion to unit norm. + + Returns + ------- + quaternion : torch.Tensor with shape (..., 4) + quaternion in ijkw order and Hamilton convention (ijk = -1) + """ + + quaternion = torch.cat( + [ + -multivector[..., [10]], + multivector[..., [9]], + -multivector[..., [8]], + multivector[..., [0]], + ], + dim=-1, + ) + + if normalize: + quaternion = quaternion / torch.linalg.norm(quaternion, dim=-1, keepdim=True) + + return quaternion diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/scalar.py b/gafl/build/geometric-algebra-transformer/gatr/interface/scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1bfcaefcb0fe30b29675d97baea5f6abcf2554 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/scalar.py @@ -0,0 +1,44 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_scalar(scalars: torch.Tensor) -> torch.Tensor: + """Embeds a scalar tensor into multivectors. + + Parameters + ---------- + scalars: torch.Tensor with shape (..., 1) + Scalar inputs. + + Returns + ------- + multivectors: torch.Tensor with shape (..., 16) + Multivector outputs. `multivectors[..., [0]]` is the same as `scalars`. The other components + are zero. + """ + + non_scalar_shape = list(scalars.shape[:-1]) + [15] + non_scalar_components = torch.zeros( + non_scalar_shape, device=scalars.device, dtype=scalars.dtype + ) + embedding = torch.cat((scalars, non_scalar_components), dim=-1) + + return embedding + + +def extract_scalar(multivectors: torch.Tensor) -> torch.Tensor: + """Extracts scalar components from multivectors. + + Parameters + ---------- + multivectors: torch.Tensor with shape (..., 16) + Multivector inputs. + + Returns + ------- + scalars: torch.Tensor with shape (..., 1) + Scalar component of multivectors. + """ + + return multivectors[..., [0]] diff --git a/gafl/build/geometric-algebra-transformer/gatr/interface/translation.py b/gafl/build/geometric-algebra-transformer/gatr/interface/translation.py new file mode 100644 index 0000000000000000000000000000000000000000..97f50b30c55119ea2890228587b54595177318b8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/interface/translation.py @@ -0,0 +1,83 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + + +def embed_translation(translation_vector: torch.Tensor) -> torch.Tensor: + """Embeds a 3D translation in multivectors. + + In our convention, a translation vector is embedded into a combination of the scalar and + bivector components. + + We have (in agreement with Eq. (82) of the reference below) that + ``` + T(t) = 1 - e_0 / 2 (t_1 e_1 + t_2 e_2 + t_3 e_3) . + ``` + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + translation_vector : torch.Tensor with shape (..., 3) + Vectorial amount of translation. + + Returns + ------- + multivector : torch.Tensor with shape (..., 16) + Embedding into multivector. + """ + + # Create multivector tensor with same batch shape, same device, same dtype as input + batch_shape = translation_vector.shape[:-1] + multivector = torch.zeros( + *batch_shape, 16, dtype=translation_vector.dtype, device=translation_vector.device + ) + + # Embedding into trivectors + multivector[..., 0] = 1.0 # scalar + multivector[..., 5:8] = ( + -0.5 * translation_vector[..., :] + ) # Translation vector embedded in x_0i with i = 1, 2, 3 + + return multivector + + +def extract_translation( + multivector: torch.Tensor, divide_by_embedding_dim=False, threshold: float = 1e-3 +) -> torch.Tensor: + """Given a multivector, extract a 3D translation vector from the bivector components. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + multivector : torch.Tensor with shape (..., 16) + Multivector. + divide_by_embedding_dim : bool + Whether to divice by the embedding dim. Proper PGA etiquette would have us do this, but it + may not be good for NN training. + threshold : float + Minimum value of the additional, unphysical component. Necessary to avoid exploding values + or NaNs when this unphysical component of the homogeneous coordinates becomes small. + + Returns + ------- + translation : torch.Tensor with shape (..., 3) + 3D components of the translation vector. + """ + + translation_vector = -2.0 * multivector[..., 5:8] + + # Divide by embedding dim + if divide_by_embedding_dim: + embedding_dim = multivector[..., [0]] + embedding_dim = torch.where(torch.abs(embedding_dim) > threshold, embedding_dim, threshold) + translation_vector = translation_vector / embedding_dim + + return translation_vector diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55575f4d3ed3bb9810576604585aea2d77329bc4 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .attention.config import SelfAttentionConfig +from .attention.positional_encoding import ApplyRotaryPositionalEncoding +from .attention.self_attention import SelfAttention +from .dropout import GradeDropout +from .layer_norm import EquiLayerNorm +from .linear import EquiLinear +from .mlp.geometric_bilinears import GeometricBilinear +from .mlp.mlp import GeoMLP +from .mlp.nonlinearities import ScalarGatedNonlinearity diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cb55ce7227c907bb4d5383128de0c4ca26adb8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .config import SelfAttentionConfig +from .self_attention import SelfAttention diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/attention.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..489fe2c99bef8b49bfc9c3a24cfa2c84b39d9513 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/attention.py @@ -0,0 +1,92 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Self-attention layers.""" + +from functools import partial + +import torch +from torch import nn + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.primitives.attention import geometric_attention, lin_square_normalizer + + +class GeometricAttention(nn.Module): + """Geometric attention layer. + + This is the main attention mechanism used in GATr. Thanks to the nonlinear features, the + scaled-dot-product attention takes into account the Euclidean distance. + + Given multivector and scalar queries, keys, and values, this layer computes: + + ``` + attn_weights[..., i, j] = softmax_j[ + weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + config : SelfAttentionConfig + Attention configuration. + """ + + def __init__(self, config: SelfAttentionConfig) -> None: + super().__init__() + + self.normalizer = partial(lin_square_normalizer, epsilon=config.normalizer_eps) + self.log_weights = nn.Parameter( + torch.zeros((config.num_heads, 1, config.hidden_mv_channels)) + ) + + def forward(self, q_mv, k_mv, v_mv, q_s, k_s, v_s, attention_mask=None): + """Forward pass through geometric attention. + + Given multivector and scalar queries, keys, and values, this forward pass computes: + + ``` + attn_weights[..., i, j] = softmax_j[ + weights[0] * pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + weights[1] * inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + + weights[2] * euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + attention_mask: None or Tensor or AttentionBias + Optional attention mask. + """ + + weights = self.log_weights.exp() + h_mv, h_s = geometric_attention( + q_mv, + k_mv, + v_mv, + q_s, + k_s, + v_s, + normalizer=self.normalizer, + weights=weights, + attn_mask=attention_mask, + ) + + return h_mv, h_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/config.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/config.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e8dd878e3a85ba0f31802d1a6ffd509f5722ba --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/config.py @@ -0,0 +1,106 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Optional + + +@dataclass +class SelfAttentionConfig: + """Configuration for attention. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + num_heads : int + Number of attention heads. + in_s_channels : int + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int + Output scalar channels. If None, no scalars are expected nor returned. + additional_qk_mv_channels : int + Whether additional multivector features for the keys and queries will be provided. + additional_qk_s_channels : int + Whether additional scalar features for the keys and queries will be provided. + normalizer : str + Normalizer function to use in sdp_dist attention + normalizer_eps : float + Small umerical constant for stability in the normalizer in sdp_dist attention + multi_query: bool + Whether to do multi-query attention + attention_type : {"scalar", "geometric", "sdp_dist"} + Whether the attention mechanism is based on the scalar product or also the join. + pos_encoding : bool + Whether to apply rotary positional embeddings along the item dimension to the scalar keys + and queries. + pos_enc_base : int + Base for the frequencies in the positional encoding. + output_init : str + Initialization scheme for final linear layer + increase_hidden_channels : int + Factor by which to increase the number of hidden channels (both multivectors and scalars) + dropout_prob : float or None + Dropout probability + """ + + multi_query: bool = True + in_mv_channels: Optional[int] = None + out_mv_channels: Optional[int] = None + in_s_channels: Optional[int] = None + out_s_channels: Optional[int] = None + num_heads: int = 8 + additional_qk_mv_channels: int = 0 + additional_qk_s_channels: int = 0 + normalizer_eps: Optional[float] = 1e-3 + pos_encoding: bool = False + pos_enc_base: int = 4096 + output_init: str = "default" + checkpoint: bool = True + increase_hidden_channels: int = 2 + dropout_prob: Optional[float] = None + + def __post_init__(self): + """Type checking / conversion.""" + if isinstance(self.dropout_prob, str) and self.dropout_prob.lower() in ["null", "none"]: + self.dropout_prob = None + + @property + def hidden_mv_channels(self) -> Optional[int]: + """Returns the number of hidden multivector channels.""" + + if self.in_mv_channels is None: + return None + + return max(self.increase_hidden_channels * self.in_mv_channels // self.num_heads, 1) + + @property + def hidden_s_channels(self) -> Optional[int]: + """Returns the number of hidden scalar channels.""" + + if self.in_s_channels is None: + return None + + hidden_s_channels = max( + self.increase_hidden_channels * self.in_s_channels // self.num_heads, 4 + ) + + # When using positional encoding, the number of scalar hidden channels needs to be even. + # It also should not be too small. + if self.pos_encoding: + hidden_s_channels = (hidden_s_channels + 1) // 2 * 2 + hidden_s_channels = max(hidden_s_channels, 8) + + return hidden_s_channels + + @classmethod + def cast(cls, config: Any) -> SelfAttentionConfig: + """Casts an object as SelfAttentionConfig.""" + if isinstance(config, SelfAttentionConfig): + return config + if isinstance(config, Mapping): + return cls(**config) + raise ValueError(f"Can not cast {config} to {cls}") diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/positional_encoding.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/positional_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..c42e107333f247ea1566136e001fced655411d23 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/positional_encoding.py @@ -0,0 +1,131 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/EleutherAI/gpt-neox/blob/737c9134bfaff7b58217d61f6619f1dcca6c484f/megatron/model/positional_embeddings.py +by EleutherAI at https://github.com/EleutherAI/gpt-neox + +Copyright (c) 2021, EleutherAI + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import torch + +from gatr.utils.einsum import cached_einsum + + +class ApplyRotaryPositionalEncoding(torch.nn.Module): + """Applies rotary position encodings (RoPE) to scalar tensors. + + References + ---------- + Jianlin Su et al, "RoFormer: Enhanced Transformer with Rotary Position Embedding", + arXiv:2104.09864 + + Parameters + ---------- + num_channels : int + Number of channels (key and query size). + item_dim : int + Embedding dimension. Should be even. + base : int + Determines the frequencies. + """ + + def __init__(self, num_channels, item_dim, base=4096): + super().__init__() + + assert ( + num_channels % 2 == 0 + ), "Number of channels needs to be even for rotary position embeddings" + + inv_freq = 1.0 / (base ** (torch.arange(0, num_channels, 2).float() / num_channels)) + self.register_buffer("inv_freq", inv_freq) + self.seq_len_cached = None + self.device_cached = None + self.cos_cached = None + self.sin_cached = None + self.item_dim = item_dim + self.num_channels = num_channels + + def forward(self, scalars: torch.Tensor) -> torch.Tensor: + """Computes rotary embeddings along `self.item_dim` and applies them to inputs. + + The inputs are usually scalar queries and keys. + + Assumes that the last dimension is the feature dimension (and is thus not suited + for multivector data!). + + Parameters + ---------- + scalars : torch.Tensor of shape (..., num_channels) + Input data. The last dimension is assumed to be the channel / feature dimension + (NOT the 16 dimensions of a multivector). + + Returns + ------- + outputs : torch.Tensor of shape (..., num_channels) + Output data. Rotary positional embeddings applied to the input tensor. + """ + + # Check inputs + assert scalars.shape[-1] == self.num_channels + + # Compute embeddings, if not already cached + self._compute_embeddings(scalars) + + # Apply embeddings + outputs = scalars * self.cos_cached + self._rotate_half(scalars) * self.sin_cached + + return outputs + + def _compute_embeddings(self, inputs): + """Computes position embeddings and stores them. + + The position embedding is computed along dimension `item_dim` of tensor `inputs` + and is stored in `self.sin_cached` and `self.cos_cached`. + + Parameters + ---------- + inputs : torch.Tensor + Input data. + """ + seq_len = inputs.shape[self.item_dim] + if seq_len != self.seq_len_cached or inputs.device != self.device_cached: + self.seq_len_cached = seq_len + self.device_cached = inputs.device + t = torch.arange(inputs.shape[self.item_dim], device=inputs.device).type_as( + self.inv_freq + ) + freqs = cached_einsum("i,j->ij", t, self.inv_freq) + emb = torch.cat((freqs, freqs), dim=-1).to(inputs.device) + + self.cos_cached = emb.cos() + self.sin_cached = emb.sin() + + # Insert appropriate amount of dimensions such that the embedding correctly enumerates + # along the item dim + item_dim = ( + self.item_dim if self.item_dim >= 0 else inputs.ndim + self.item_dim + ) # Deal with item_dim < 0 + for _ in range(item_dim + 1, inputs.ndim - 1): + self.cos_cached = self.cos_cached.unsqueeze(1) + self.sin_cached = self.sin_cached.unsqueeze(1) + + @staticmethod + def _rotate_half(inputs): + """Utility function that "rotates" a tensor, as required for rotary embeddings.""" + x1, x2 = inputs[..., : inputs.shape[-1] // 2], inputs[..., inputs.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/qkv.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/qkv.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce1503438a15a0ab83f1f74e51e6ad0b7cf91d3 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/qkv.py @@ -0,0 +1,209 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch +from einops import rearrange +from torch import nn + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.linear import EquiLinear + + +class QKVModule(nn.Module): + """Compute (multivector and scalar) queries, keys, and values via multi-head attention. + + Parameters + ---------- + config: SelfAttentionConfig + Attention configuration + """ + + def __init__(self, config: SelfAttentionConfig): + super().__init__() + self.in_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=3 * config.hidden_mv_channels * config.num_heads, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=None + if config.in_s_channels is None + else 3 * config.hidden_s_channels * config.num_heads, + ) + self.config = config + + def forward( + self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None + ): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Multivector inputs + scalars : torch.Tensor + Scalar inputs + additional_qk_features_mv : None or torch.Tensor + Additional multivector features that should be provided for the Q/K computation (e.g. + positions of objects) + additional_qk_features_s : None or torch.Tensor + Additional scalar features that should be provided for the Q/K computation (e.g. + object types) + + Returns + ------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + """ + + # Additional inputs + if additional_qk_features_mv is not None: + inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2) + if additional_qk_features_s is not None: + scalars = torch.cat((scalars, additional_qk_features_s), dim=-1) + + qkv_mv, qkv_s = self.in_linear( + inputs, scalars + ) # (..., num_items, 3 * hidden_channels * num_heads, 16) + qkv_mv = rearrange( + qkv_mv, + "... items (qkv hidden num_heads) x -> qkv ... num_heads items hidden x", + num_heads=self.config.num_heads, + hidden=self.config.hidden_mv_channels, + qkv=3, + ) + q_mv, k_mv, v_mv = qkv_mv # each: (..., num_heads, num_items, num_channels, 16) + + # Same, for optional scalar components + if qkv_s is not None: + qkv_s = rearrange( + qkv_s, + "... items (qkv hidden num_heads) -> qkv ... num_heads items hidden", + num_heads=self.config.num_heads, + hidden=self.config.hidden_s_channels, + qkv=3, + ) + q_s, k_s, v_s = qkv_s # each: (..., num_heads, num_items, num_channels) + else: + q_s, k_s, v_s = None, None, None + + return q_mv, k_mv, v_mv, q_s, k_s, v_s + + +class MultiQueryQKVModule(nn.Module): + """Compute (multivector and scalar) queries, keys, and values via multi-query attention. + + Parameters + ---------- + config: SelfAttentionConfig + Attention configuration + """ + + def __init__(self, config: SelfAttentionConfig): + super().__init__() + + # Q projection + self.q_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=config.hidden_mv_channels * config.num_heads, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=config.hidden_s_channels * config.num_heads, + ) + + # Key and value projections (shared between heads) + self.k_linear = EquiLinear( + in_mv_channels=config.in_mv_channels + config.additional_qk_mv_channels, + out_mv_channels=config.hidden_mv_channels, + in_s_channels=config.in_s_channels + config.additional_qk_s_channels, + out_s_channels=config.hidden_s_channels, + ) + self.v_linear = EquiLinear( + in_mv_channels=config.in_mv_channels, + out_mv_channels=config.hidden_mv_channels, + in_s_channels=config.in_s_channels, + out_s_channels=config.hidden_s_channels, + ) + self.config = config + + def forward( + self, inputs, scalars, additional_qk_features_mv=None, additional_qk_features_s=None + ): + """Forward pass. + + Parameters + ---------- + inputs : torch.Tensor + Multivector inputs + scalars : torch.Tensor + Scalar inputs + additional_qk_features_mv : None or torch.Tensor + Additional multivector features that should be provided for the Q/K computation (e.g. + positions of objects) + additional_qk_features_s : None or torch.Tensor + Additional scalar features that should be provided for the Q/K computation (e.g. + object types) + + Returns + ------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + """ + + # Additional inputs + if additional_qk_features_mv is not None: + qk_inputs = torch.cat((inputs, additional_qk_features_mv), dim=-2) + else: + qk_inputs = inputs + if scalars is not None and additional_qk_features_s is not None: + qk_scalars = torch.cat((scalars, additional_qk_features_s), dim=-1) + else: + qk_scalars = scalars + + # Project to queries, keys, and values (multivector reps) + q_mv, q_s = self.q_linear( + qk_inputs, qk_scalars + ) # (..., num_items, hidden_channels * num_heads, 16) + k_mv, k_s = self.k_linear(qk_inputs, qk_scalars) # (..., num_items, hidden_channels, 16) + v_mv, v_s = self.v_linear(inputs, scalars) # (..., num_items, hidden_channels, 16) + + # Rearrange to (..., heads, items, channels, 16) shape + q_mv = rearrange( + q_mv, + "... items (hidden_channels num_heads) x -> ... num_heads items hidden_channels x", + num_heads=self.config.num_heads, + hidden_channels=self.config.hidden_mv_channels, + ) + k_mv = rearrange(k_mv, "... items hidden_channels x -> ... 1 items hidden_channels x") + v_mv = rearrange(v_mv, "... items hidden_channels x -> ... 1 items hidden_channels x") + + # Same for scalars + if q_s is not None: + q_s = rearrange( + q_s, + "... items (hidden_channels num_heads) -> ... num_heads items hidden_channels", + num_heads=self.config.num_heads, + hidden_channels=self.config.hidden_s_channels, + ) + k_s = rearrange(k_s, "... items hidden_channels -> ... 1 items hidden_channels") + v_s = rearrange(v_s, "... items hidden_channels -> ... 1 items hidden_channels") + else: + q_s, k_s, v_s = None, None, None + + return q_mv, k_mv, v_mv, q_s, k_s, v_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/attention/self_attention.py b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/self_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d46d52ef5b70a96f667d6ead204179d2496fa --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/attention/self_attention.py @@ -0,0 +1,143 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Self-attention layers.""" + +from typing import Optional, Tuple + +import torch +from einops import rearrange +from torch import nn + +from gatr.layers.attention.attention import GeometricAttention +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.attention.positional_encoding import ApplyRotaryPositionalEncoding +from gatr.layers.attention.qkv import MultiQueryQKVModule, QKVModule +from gatr.layers.dropout import GradeDropout +from gatr.layers.linear import EquiLinear + + +class SelfAttention(nn.Module): + """Geometric self-attention layer. + + Constructs queries, keys, and values, computes attention, and projects linearly to outputs. + + Parameters + ---------- + config : SelfAttentionConfig + Attention configuration. + """ + + def __init__(self, config: SelfAttentionConfig) -> None: + super().__init__() + + # Store settings + self.config = config + + # QKV computation + self.qkv_module = MultiQueryQKVModule(config) if config.multi_query else QKVModule(config) + + # Output projection + self.out_linear = EquiLinear( + in_mv_channels=config.hidden_mv_channels * config.num_heads, + out_mv_channels=config.out_mv_channels, + in_s_channels=None + if config.in_s_channels is None + else config.hidden_s_channels * config.num_heads, + out_s_channels=config.out_s_channels, + initialization=config.output_init, + ) + + # Optional positional encoding + self.pos_encoding: nn.Module + if config.pos_encoding: + self.pos_encoding = ApplyRotaryPositionalEncoding( + config.hidden_s_channels, item_dim=-2, base=config.pos_enc_base + ) + else: + self.pos_encoding = nn.Identity() + + # Attention + self.attention = GeometricAttention(config) + + # Dropout + self.dropout: Optional[nn.Module] + if config.dropout_prob is not None: + self.dropout = GradeDropout(config.dropout_prob) + else: + self.dropout = None + + def forward( + self, + multivectors: torch.Tensor, + additional_qk_features_mv: Optional[torch.Tensor] = None, + scalars: Optional[torch.Tensor] = None, + additional_qk_features_s: Optional[torch.Tensor] = None, + attention_mask=None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes forward pass on inputs with shape `(..., items, channels, 16)`. + + The result is the following: + + ``` + # For each head + queries = linear_channels(inputs) + keys = linear_channels(inputs) + values = linear_channels(inputs) + hidden = attention_items(queries, keys, values, biases=biases) + head_output = linear_channels(hidden) + + # Combine results + output = concatenate_heads head_output + ``` + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., num_items, channels_in, 16) + Input multivectors. + additional_qk_features_mv : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, multivector part. + scalars : None or torch.Tensor with shape (..., num_items, num_items, in_scalars) + Optional input scalars + additional_qk_features_s : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, scalar part. + scalars : None or torch.Tensor with shape (..., num_items, num_items, in_scalars) + Optional input scalars + attention_mask: None or torch.Tensor with shape (..., num_items, num_items) + Optional attention mask + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., num_items, channels_out, 16) + Output multivectors. + output_scalars : torch.Tensor with shape (..., num_items, channels_out, out_scalars) + Output scalars, if scalars are provided. Otherwise None. + """ + # Compute Q, K, V + q_mv, k_mv, v_mv, q_s, k_s, v_s = self.qkv_module( + multivectors, scalars, additional_qk_features_mv, additional_qk_features_s + ) + + # Rotary positional encoding + q_s = self.pos_encoding(q_s) + k_s = self.pos_encoding(k_s) + + # Attention layer + h_mv, h_s = self.attention(q_mv, k_mv, v_mv, q_s, k_s, v_s, attention_mask=attention_mask) + + h_mv = rearrange( + h_mv, "... n_heads n_items hidden_channels x -> ... n_items (n_heads hidden_channels) x" + ) + h_s = rearrange( + h_s, "... n_heads n_items hidden_channels -> ... n_items (n_heads hidden_channels)" + ) + + # Transform linearly one more time + outputs_mv, outputs_s = self.out_linear(h_mv, scalars=h_s) + + # Dropout + if self.dropout is not None: + outputs_mv, outputs_s = self.dropout(outputs_mv, outputs_s) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/dropout.py b/gafl/build/geometric-algebra-transformer/gatr/layers/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce686bbd20ed18a9c2a61bdc2732f5f2de21171 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/dropout.py @@ -0,0 +1,49 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant dropout layer.""" + +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives import grade_dropout + + +class GradeDropout(nn.Module): + """Grade dropout for multivectors (and regular dropout for auxiliary scalars). + + Parameters + ---------- + p : float + Dropout probability. + """ + + def __init__(self, p: float = 0.0): + super().__init__() + self._dropout_prob = p + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. Applies dropout. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., 16) + Multivector inputs. + scalars : torch.Tensor + Scalar inputs. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., 16) + Multivector inputs with dropout applied. + output_scalars : torch.Tensor + Scalar inputs with dropout applied. + """ + + out_mv = grade_dropout(multivectors, p=self._dropout_prob, training=self.training) + out_s = torch.nn.functional.dropout(scalars, p=self._dropout_prob, training=self.training) + + return out_mv, out_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/gatr_block.py b/gafl/build/geometric-algebra-transformer/gatr/layers/gatr_block.py new file mode 100644 index 0000000000000000000000000000000000000000..ee96806de22e9a27a3e6d3a36276e8c8fb274049 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/gatr_block.py @@ -0,0 +1,141 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from dataclasses import replace +from typing import Optional, Tuple + +import torch +from torch import nn + +from gatr.layers import SelfAttention, SelfAttentionConfig +from gatr.layers.layer_norm import EquiLayerNorm +from gatr.layers.mlp.config import MLPConfig +from gatr.layers.mlp.mlp import GeoMLP + + +class GATrBlock(nn.Module): + """Equivariant transformer block for GATr. + + This is the biggest building block of GATr. + + Inputs are first processed by a block consisting of LayerNorm, multi-head geometric + self-attention, and a residual connection. Then the data is processed by a block consisting of + another LayerNorm, an item-wise two-layer geometric MLP with GeLU activations, and another + residual connection. + + Parameters + ---------- + mv_channels : int + Number of input and output multivector channels + s_channels: int + Number of input and output scalar channels + attention: SelfAttentionConfig + Attention configuration + mlp: MLPConfig + MLP configuration + dropout_prob : float or None + Dropout probability + """ + + def __init__( + self, + mv_channels: int, + s_channels: int, + attention: SelfAttentionConfig, + mlp: MLPConfig, + dropout_prob: Optional[float] = None, + ) -> None: + super().__init__() + + # Normalization layer (stateless, so we can use the same layer for both normalization + # instances) + self.norm = EquiLayerNorm() + + # Self-attention layer + attention = replace( + attention, + in_mv_channels=mv_channels, + out_mv_channels=mv_channels, + in_s_channels=s_channels, + out_s_channels=s_channels, + output_init="small", + dropout_prob=dropout_prob, + ) + self.attention = SelfAttention(attention) + + # MLP block + mlp = replace( + mlp, + mv_channels=(mv_channels, 2 * mv_channels, mv_channels), + s_channels=(s_channels, 2 * s_channels, s_channels), + dropout_prob=dropout_prob, + ) + self.mlp = GeoMLP(mlp) + + def forward( + self, + multivectors: torch.Tensor, + scalars: torch.Tensor, + reference_mv=None, + additional_qk_features_mv=None, + additional_qk_features_s=None, + attention_mask=None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass of the transformer block. + + Inputs are first processed by a block consisting of LayerNorm, multi-head geometric + self-attention, and a residual connection. Then the data is processed by a block consisting + of another LayerNorm, an item-wise two-layer geometric MLP with GeLU activations, and + another residual connection. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., items, channels, 16) + Input multivectors. + scalars : torch.Tensor with shape (..., s_channels) + Input scalars. + reference_mv : torch.Tensor with shape (..., 16) or None + Reference multivector for the equivariant join operation in the MLP. + additional_qk_features_mv : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, multivector part. + additional_qk_features_s : None or torch.Tensor with shape + (..., num_items, add_qk_mv_channels, 16) + Additional Q/K features, scalar part. + attention_mask: None or torch.Tensor or AttentionBias + Optional attention mask. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., items, channels, 16). + Output multivectors + output_scalars : torch.Tensor with shape (..., s_channels) + Output scalars + """ + + # Attention block: layer norm + h_mv, h_s = self.norm(multivectors, scalars=scalars) + + # Attention block: self attention + h_mv, h_s = self.attention( + h_mv, + scalars=h_s, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + + # Attention block: skip connection + outputs_mv = multivectors + h_mv + outputs_s = scalars + h_s + + # MLP block: layer norm + h_mv, h_s = self.norm(outputs_mv, scalars=outputs_s) + + # MLP block: MLP + h_mv, h_s = self.mlp(h_mv, scalars=h_s, reference_mv=reference_mv) + + # MLP block: skip connection + outputs_mv = outputs_mv + h_mv + outputs_s = outputs_s + h_s + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/layer_norm.py b/gafl/build/geometric-algebra-transformer/gatr/layers/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f9301a78f541ce03b576c96220f0c49c5c5a55 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/layer_norm.py @@ -0,0 +1,70 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant normalization layers.""" + +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives import equi_layer_norm + + +class EquiLayerNorm(nn.Module): + """Equivariant LayerNorm for multivectors. + + Rescales input such that `mean_channels |inputs|^2 = 1`, where the norm is the GA norm and the + mean goes over the channel dimensions. + + In addition, the layer performs a regular LayerNorm operation on auxiliary scalar inputs. + + Parameters + ---------- + mv_channel_dim : int + Channel dimension index for multivector inputs. Defaults to the second-last entry (last are + the multivector components). + scalar_channel_dim : int + Channel dimension index for scalar inputs. Defaults to the last entry. + epsilon : float + Small numerical factor to avoid instabilities. We use a reasonably large number to balance + issues that arise from some multivector components not contributing to the norm. + """ + + def __init__(self, mv_channel_dim=-2, scalar_channel_dim=-1, epsilon: float = 0.01): + super().__init__() + self.mv_channel_dim = mv_channel_dim + self.epsilon = epsilon + + if scalar_channel_dim != -1: + raise NotImplementedError( + "Currently, only scalar_channel_dim = -1 is implemented, but found" + f" {scalar_channel_dim}" + ) + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. Computes equivariant LayerNorm for multivectors. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., 16) + Multivector inputs + scalars : torch.Tensor with shape (..., self.in_channels, self.in_scalars) + Scalar inputs + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., 16) + Normalized multivectors + output_scalars : torch.Tensor with shape (..., self.out_channels, self.in_scalars) + Normalized scalars. + """ + + outputs_mv = equi_layer_norm( + multivectors, channel_dim=self.mv_channel_dim, epsilon=self.epsilon + ) + normalized_shape = scalars.shape[-1:] + outputs_s = torch.nn.functional.layer_norm(scalars, normalized_shape=normalized_shape) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/linear.py b/gafl/build/geometric-algebra-transformer/gatr/layers/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f9b57180b740ef4f0121ac805564324261b603 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/linear.py @@ -0,0 +1,355 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Pin-equivariant linear layers between multivector tensors (torch.nn.Modules).""" + +from typing import Optional, Tuple, Union + +import numpy as np +import torch +from torch import nn + +from gatr.interface import embed_scalar +from gatr.primitives.linear import NUM_PIN_LINEAR_BASIS_ELEMENTS, equi_linear + + +class EquiLinear(nn.Module): + """Pin-equivariant linear layer. + + The forward pass maps multivector inputs with shape (..., in_channels, 16) to multivector + outputs with shape (..., out_channels, 16) as + + ``` + outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x] + ``` + + plus an optional bias term for outputs[..., :, 0] (biases in other multivector components would + break equivariance). + + Here basis_map are precomputed (see gatr.primitives.linear) and weights are the + learnable weights of this layer. + + If there are auxiliary input scalars, they transform under a linear layer, and mix with the + scalar components the multivector data. Note that in this layer (and only here) the auxiliary + scalars are optional. + + This layer supports four initialization schemes: + - "default": preserves (or actually slightly reducing) the variance of the data in + the forward pass + - "small": variance of outputs is approximately one order of magnitude smaller + than for "default" + - "unit_scalar": outputs will be close to (1, 0, 0, ..., 0) + - "almost_unit_scalar": similar to "unit_scalar", but with more stochasticity + + Parameters + ---------- + in_mv_channels : int + Input multivector channels + out_mv_channels : int + Output multivector channels + bias : bool + Whether a bias term is added to the scalar component of the multivector outputs + in_s_channels : int or None + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + initialization : {"default", "small", "unit_scalar", "almost_unit_scalar"} + Initialization scheme. For "default", initialize with the same philosophy as most + networks do: preserve variance (approximately) in the forward pass. For "small", + initalize the network such that the variance of the output data is approximately one + order of magnitude smaller than that of the input data. For "unit_scalar", initialize + the layer such that the output multivectors will be closer to (1, 0, 0, ..., 0). + "almost_unit_scalar" is similar, but with more randomness. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + bias: bool = True, + initialization: str = "default", + ) -> None: + super().__init__() + + # Check inputs + if initialization == "unit_scalar": + assert bias, "unit_scalar initialization requires bias" + if in_s_channels is None: + raise NotImplementedError( + "unit_scalar initialization is currently only implemented for scalar inputs" + ) + + self._in_mv_channels = in_mv_channels + + # MV -> MV + self.weight = nn.Parameter( + torch.empty((out_mv_channels, in_mv_channels, NUM_PIN_LINEAR_BASIS_ELEMENTS)) + ) + + # We only need a separate bias here if that isn't already covered by the linear map from + # scalar inputs + self.bias = ( + nn.Parameter(torch.zeros((out_mv_channels, 1))) + if bias and in_s_channels is None + else None + ) + + # Scalars -> MV scalars + self.s2mvs: Optional[nn.Linear] + if in_s_channels: + self.s2mvs = nn.Linear(in_s_channels, out_mv_channels, bias=bias) + else: + self.s2mvs = None + + # MV scalars -> scalars + if out_s_channels: + self.mvs2s = nn.Linear(in_mv_channels, out_s_channels, bias=bias) + else: + self.mvs2s = None + + # Scalars -> scalars + if in_s_channels is not None and out_s_channels is not None: + self.s2s = nn.Linear( + in_s_channels, out_s_channels, bias=False + ) # Bias would be duplicate + else: + self.s2s = None + + # Initialization + self.reset_parameters(initialization) + + def forward( + self, multivectors: torch.Tensor, scalars: Optional[torch.Tensor] = None + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Maps input multivectors and scalars using the most general equivariant linear map. + + The result is again multivectors and scalars. + + For multivectors we have: + ``` + outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x] + = sum_i linear(inputs[..., i, :], weights[j, i, :]) + ``` + + Here basis_map are precomputed (see gatr.primitives.linear) and weights are the + learnable weights of this layer. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + outputs_mv = equi_linear(multivectors, self.weight) # (..., out_channels, 16) + + if self.bias is not None: + bias = embed_scalar(self.bias) + outputs_mv = outputs_mv + bias + + if self.s2mvs is not None and scalars is not None: + outputs_mv[..., 0] += self.s2mvs(scalars) + + if self.mvs2s is not None: + outputs_s = self.mvs2s(multivectors[..., 0]) + if self.s2s is not None and scalars is not None: + outputs_s = outputs_s + self.s2s(scalars) + else: + outputs_s = None + + return outputs_mv, outputs_s + + def reset_parameters( + self, + initialization: str, + gain: float = 1.0, + additional_factor=1.0 / np.sqrt(3.0), + use_mv_heuristics=True, + ) -> None: + """Initializes the weights of the layer. + + Parameters + ---------- + initialization : {"default", "small", "unit_scalar", "almost_unit_scalar"} + Initialization scheme. For "default", initialize with the same philosophy as most + networks do: preserve variance (approximately) in the forward pass. For "small", + initalize the network such that the variance of the output data is approximately one + order of magnitude smaller than that of the input data. For "unit_scalar", initialize + the layer such that the output multivectors will be closer to (1, 0, 0, ..., 0). + "almost_unit_scalar" is similar, but with more randomness. + gain : float + Gain factor for the activations. Should be 1.0 if previous layer has no activation, + sqrt(2) if it has a ReLU activation, and so on. Can be computed with + `torch.nn.init.calculate_gain()`. + additional_factor : float + Empirically, it has been found that slightly *decreasing* the data variance at each + layer gives a better performance. In particular, the PyTorch default initialization uses + an additional factor of 1/sqrt(3) (cancelling the factor of sqrt(3) that naturally + arises when computing the bounds of a uniform initialization). A discussion of this was + (to the best of our knowledge) never published, but see + https://github.com/pytorch/pytorch/issues/57109 and + https://soumith.ch/files/20141213_gplus_nninit_discussion.htm. + use_mv_heuristics : bool + Multivector components are differently affected by the equivariance constraint. If + `use_mv_heuristics` is set to True, we initialize the weights for each output + multivector component differently, with factors determined empirically to preserve the + variance of each multivector component in the forward pass. + """ + + # Prefactors depending on initialization scheme + mv_component_factors, mv_factor, mvs_bias_shift, s_factor = self._compute_init_factors( + initialization, gain, additional_factor, use_mv_heuristics + ) + + # Following He et al, 1502.01852, we aim to preserve the variance in the forward pass. + # A sufficient criterion for this is that the variance of the weights is given by + # `Var[w] = gain^2 / fan`. + # Here `gain^2` is 2 if the previous layer has a ReLU nonlinearity, 1 for the initial layer, + # and some other value in other situations (we may not care about this too much). + # More importantly, `fan` is the number of connections: the number of input elements that + # get summed over to compute each output element. + + # Let us fist consider the multivector outputs. + self._init_multivectors(mv_component_factors, mv_factor, mvs_bias_shift) + + # Then let's consider the maps to scalars. + self._init_scalars(s_factor) + + @staticmethod + def _compute_init_factors(initialization, gain, additional_factor, use_mv_heuristics): + """Computes prefactors for the initialization. + + See self.reset_parameters(). + """ + + if initialization not in {"default", "small", "unit_scalar", "almost_unit_scalar"}: + raise ValueError(f"Unknown initialization scheme {initialization}") + + if initialization == "default": + mv_factor = gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 0.0 + elif initialization == "small": + # Change scale by a factor of 0.3 in this layer + mv_factor = 0.1 * gain * additional_factor * np.sqrt(3) + s_factor = 0.1 * gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 0.0 + elif initialization == "unit_scalar": + # Change scale by a factor of 0.3 for MV outputs, and initialize bias around 1 + mv_factor = 0.1 * gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 1.0 + elif initialization == "almost_unit_scalar": + # Change scale by a factor of 0.3 for MV outputs, and initialize bias around 1 + mv_factor = 0.5 * gain * additional_factor * np.sqrt(3) + s_factor = gain * additional_factor * np.sqrt(3) + mvs_bias_shift = 1.0 + else: + raise ValueError( + f"Unknown initialization scheme {initialization}, expected" + ' "default", "small", or "unit_scalar".' + ) + + # Individual factors for each multivector component + if use_mv_heuristics: + # Without corrections, the variance of standard normal inputs after a forward pass + # through this layer is different for each output grade. The reason is that the + # equivariance constraints affect different grades differently. + # We heuristically correct for this by initializing the weights for different basis + # elements differently, using the following additional factors on the weight bound: + # mv_component_factors = torch.sqrt(torch.Tensor([0.5, 4.0, 6.0, 4.0, 1.0, 0.5, 0.5])) + mv_component_factors = torch.sqrt( + torch.Tensor([1.0, 4.0, 6.0, 2.0, 0.5, 0.5, 1.5, 1.5, 0.5]) + ) + else: + mv_component_factors = torch.ones(NUM_PIN_LINEAR_BASIS_ELEMENTS) + return mv_component_factors, mv_factor, mvs_bias_shift, s_factor + + def _init_multivectors(self, mv_component_factors, mv_factor, mvs_bias_shift): + """Weight initialization for maps to multivector outputs.""" + + # We have + # `outputs[..., j, y] = sum_{i, b, x} weights[j, i, b] basis_map[b, x, y] inputs[..., i, x]` + # The basis maps are more or less grade projections, summing over all basis elements + # corresponds to (almost) an identity map in the GA space. The sum over `b` and `x` thus + # does not contribute to `fan` substantially. (We may add a small ad-hoc factor later to + # make up for this approximation.) However, there is still the sum over incoming channels, + # and thus `fan ~ mv_in_channels`. Assuming (for now) that the previous layer contained a + # ReLU activation, we finally have the condition `Var[w] = 2 / mv_in_channels`. + # Since the variance of a uniform distribution between -a and a is given by + # `Var[Uniform(-a, a)] = a^2/3`, we should set `a = gain * sqrt(3 / mv_in_channels)`. + # In theory (see docstring). + fan_in = self._in_mv_channels + bound = mv_factor / np.sqrt(fan_in) + for i, factor in enumerate(mv_component_factors): + nn.init.uniform_(self.weight[..., i], a=-factor * bound, b=factor * bound) + + # Now let's focus on the scalar components of the multivector outputs. + # If there are only multivector inputs, all is good. But if scalar inputs contribute them as + # well, they contribute to the output variance as well. + # In this case, we initialize such that the multivector inputs and the scalar inputs each + # contribute half to the output variance. + # We can achieve this by inspecting the basis maps and seeing that only basis element 0 + # contributes to the scalar output. Thus, we can reduce the variance of the correponding + # weights to give a variance of 0.5, not 1. + if self.s2mvs is not None: + bound = mv_component_factors[0] * mv_factor / np.sqrt(fan_in) / np.sqrt(2) + nn.init.uniform_(self.weight[..., [0]], a=-bound, b=bound) + + # The same holds for the scalar-to-MV map, where we also just want a variance of 0.5. + if self.s2mvs is not None: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out( + self.s2mvs.weight + ) # pylint:disable=protected-access + fan_in = max(fan_in, 1) # Since in theory we could have 0-channel scalar "data" + bound = mv_component_factors[0] * mv_factor / np.sqrt(fan_in) / np.sqrt(2) + nn.init.uniform_(self.s2mvs.weight, a=-bound, b=bound) + + # Bias needs to be adapted, as the overall fan in is different (need to account for MV + # and s inputs) and we may need to account for the unit_scalar initialization scheme + if self.s2mvs.bias is not None: + fan_in = ( + nn.init._calculate_fan_in_and_fan_out(self.s2mvs.weight)[0] + + self._in_mv_channels + ) + bound = mv_component_factors[0] / np.sqrt(fan_in) if fan_in > 0 else 0 + nn.init.uniform_(self.s2mvs.bias, mvs_bias_shift - bound, mvs_bias_shift + bound) + + def _init_scalars(self, s_factor): + """Weight initialization for maps to multivector outputs.""" + + # If both exist, we need to account for overcounting again, and assign each a target a + # variance of 0.5. + models = [] + if self.s2s: + models.append(self.s2s) + if self.mvs2s: + models.append(self.mvs2s) + for model in models: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out( + model.weight + ) # pylint:disable=protected-access + fan_in = max(fan_in, 1) # Since in theory we could have 0-channel scalar "data" + bound = s_factor / np.sqrt(fan_in) / np.sqrt(len(models)) + nn.init.uniform_(model.weight, a=-bound, b=bound) + # Bias needs to be adapted, as the overall fan in is different (need to account for MV and + # s inputs) + if self.mvs2s and self.mvs2s.bias is not None: + fan_in = nn.init._calculate_fan_in_and_fan_out(self.mvs2s.weight)[ + 0 + ] # pylint:disable=protected-access + if self.s2s: + fan_in += nn.init._calculate_fan_in_and_fan_out(self.s2s.weight)[ + 0 + ] # pylint:disable=protected-access + bound = s_factor / np.sqrt(fan_in) if fan_in > 0 else 0 + nn.init.uniform_(self.mvs2s.bias, -bound, bound) diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..748dc70faf9eaa7f5c4345b956a92c79079fadc0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .config import MLPConfig +from .geometric_bilinears import GeometricBilinear +from .mlp import GeoMLP +from .nonlinearities import ScalarGatedNonlinearity diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/config.py b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0eebccd677423ba87bb996ce340df84e326b8d92 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/config.py @@ -0,0 +1,43 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, List, Mapping, Optional + + +@dataclass +class MLPConfig: + """Geometric MLP configuration. + + Parameters + ---------- + mv_channels : iterable of int + Number of multivector channels at each layer, from input to output + s_channels : None or iterable of int + If not None, sets the number of scalar channels at each layer, from input to output. Length + needs to match mv_channels + activation : {"relu", "sigmoid", "gelu"} + Which (gated) activation function to use + dropout_prob : float or None + Dropout probability + """ + + mv_channels: Optional[List[int]] = None + s_channels: Optional[List[int]] = None + activation: str = "gelu" + dropout_prob: Optional[float] = None + + def __post_init__(self): + """Type checking / conversion.""" + if isinstance(self.dropout_prob, str) and self.dropout_prob.lower() in ["null", "none"]: + self.dropout_prob = None + + @classmethod + def cast(cls, config: Any) -> MLPConfig: + """Casts an object as MLPConfig.""" + if isinstance(config, MLPConfig): + return config + if isinstance(config, Mapping): + return cls(**config) + raise ValueError(f"Can not cast {config} to {cls}") diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/geometric_bilinears.py b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/geometric_bilinears.py new file mode 100644 index 0000000000000000000000000000000000000000..e51f53ee59fe90c43dbacdca827f814446b60527 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/geometric_bilinears.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Pin-equivariant geometric product layer between multivector tensors (torch.nn.Modules).""" + +from typing import Optional, Tuple + +import torch +from torch import nn + +from gatr.layers.linear import EquiLinear +from gatr.primitives import equivariant_join, geometric_product + + +class GeometricBilinear(nn.Module): + """Geometric bilinear layer. + + Pin-equivariant map between multivector tensors that constructs new geometric features via + geometric products and the equivariant join (based on a reference vector). + + Parameters + ---------- + in_mv_channels : int + Input multivector channels of `x` + out_mv_channels : int + Output multivector channels + hidden_mv_channels : int or None + Hidden MV channels. If None, uses out_mv_channels. + in_s_channels : int or None + Input scalar channels of `x`. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: Optional[int] = None, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + ) -> None: + super().__init__() + + # Default options + if hidden_mv_channels is None: + hidden_mv_channels = out_mv_channels + + out_mv_channels_each = hidden_mv_channels // 2 + assert ( + out_mv_channels_each * 2 == hidden_mv_channels + ), "GeometricBilinear needs even channel number" + + # Linear projections for GP + self.linear_left = EquiLinear( + in_mv_channels, + out_mv_channels_each, + in_s_channels=in_s_channels, + out_s_channels=None, + ) + self.linear_right = EquiLinear( + in_mv_channels, + out_mv_channels_each, + in_s_channels=in_s_channels, + out_s_channels=None, + initialization="almost_unit_scalar", + ) + + # Linear projections for join + self.linear_join_left = EquiLinear( + in_mv_channels, out_mv_channels_each, in_s_channels=in_s_channels, out_s_channels=None + ) + self.linear_join_right = EquiLinear( + in_mv_channels, out_mv_channels_each, in_s_channels=in_s_channels, out_s_channels=None + ) + + # Output linear projection + self.linear_out = EquiLinear( + hidden_mv_channels, out_mv_channels, in_s_channels, out_s_channels + ) + + def forward( + self, + multivectors: torch.Tensor, + reference_mv: torch.Tensor, + scalars: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Forward pass. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : torch.Tensor with shape (..., in_s_channels) + Input scalars + reference_mv : torch.Tensor with shape (..., 16) + Reference multivector for equivariant join. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., self.out_mv_channels, 16) + Output multivectors + output_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars. + """ + + # GP + left, _ = self.linear_left(multivectors, scalars=scalars) + right, _ = self.linear_right(multivectors, scalars=scalars) + gp_outputs = geometric_product(left, right) + + # Equivariant join + left, _ = self.linear_join_left(multivectors, scalars=scalars) + right, _ = self.linear_join_right(multivectors, scalars=scalars) + join_outputs = equivariant_join(left, right, reference_mv) + + # Output linear + outputs_mv = torch.cat((gp_outputs, join_outputs), dim=-2) + outputs_mv, outputs_s = self.linear_out(outputs_mv, scalars=scalars) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/mlp.py b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..b226ff21f2b25a21c7ba76d226e2b54a759c5d83 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/mlp.py @@ -0,0 +1,101 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Factory functions for simple MLPs for multivector data.""" + +from typing import List, Tuple, Union + +import torch +from torch import nn + +from gatr.layers.dropout import GradeDropout +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.layers.mlp.geometric_bilinears import GeometricBilinear +from gatr.layers.mlp.nonlinearities import ScalarGatedNonlinearity + + +class GeoMLP(nn.Module): + """Geometric MLP. + + This is a core component of GATr's transformer blocks. It is similar to a regular MLP, except + that it uses geometric bilinears (GP and equivariant join) in place of the first linear layer. + + Assumes input has shape `(..., channels[0], 16)`, output has shape `(..., channels[-1], 16)`, + will create hidden layers with shape `(..., channel, 16)` for each additional entry in + `channels`. + + Parameters + ---------- + config: MLPConfig + Configuration object + """ + + def __init__( + self, + config: MLPConfig, + ) -> None: + super().__init__() + + # Store settings + self.config = config + + assert config.mv_channels is not None + s_channels = ( + [None for _ in config.mv_channels] if config.s_channels is None else config.s_channels + ) + + layers: List[nn.Module] = [] + + if len(config.mv_channels) >= 2: + layers.append( + GeometricBilinear( + in_mv_channels=config.mv_channels[0], + out_mv_channels=config.mv_channels[1], + in_s_channels=s_channels[0], + out_s_channels=s_channels[1], + ) + ) + if config.dropout_prob is not None: + layers.append(GradeDropout(config.dropout_prob)) + + for in_, out, in_s, out_s in zip( + config.mv_channels[1:-1], config.mv_channels[2:], s_channels[1:-1], s_channels[2:] + ): + layers.append(ScalarGatedNonlinearity(config.activation)) + layers.append(EquiLinear(in_, out, in_s_channels=in_s, out_s_channels=out_s)) + if config.dropout_prob is not None: + layers.append(GradeDropout(config.dropout_prob)) + + self.layers = nn.ModuleList(layers) + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor, reference_mv: torch.Tensor + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Forward pass. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors. + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars. + reference_mv : torch.Tensor with shape (..., 16) + Reference multivector for equivariant join. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors. + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + mv, s = multivectors, scalars + + for i, layer in enumerate(self.layers): + if i == 0: + mv, s = layer(mv, scalars=s, reference_mv=reference_mv) + else: + mv, s = layer(mv, scalars=s) + + return mv, s diff --git a/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/nonlinearities.py b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..2758002e706f3e999131f472fa8d688a38dcbdf6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/layers/mlp/nonlinearities.py @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Tuple + +import torch +from torch import nn + +from gatr.primitives.nonlinearities import gated_gelu, gated_relu, gated_sigmoid + + +class ScalarGatedNonlinearity(nn.Module): + """Gated nonlinearity, where the gate is simply given by the scalar component of the input. + + Given multivector input x, computes f(x_0) * x, where f can either be ReLU, sigmoid, or GeLU. + + Auxiliary scalar inputs are simply processed with ReLU, sigmoid, or GeLU, without gating. + + Parameters + ---------- + nonlinearity : {"relu", "sigmoid", "gelu"} + Non-linearity type + """ + + def __init__(self, nonlinearity: str = "relu", **kwargs) -> None: + super().__init__() + + gated_fn_dict = dict(relu=gated_relu, gelu=gated_gelu, sigmoid=gated_sigmoid) + scalar_fn_dict = dict( + relu=nn.functional.relu, gelu=nn.functional.gelu, sigmoid=nn.functional.sigmoid + ) + try: + self.gated_nonlinearity = gated_fn_dict[nonlinearity] + self.scalar_nonlinearity = scalar_fn_dict[nonlinearity] + except KeyError as exc: + raise ValueError( + f"Unknown nonlinearity {nonlinearity} for options {list(gated_fn_dict.keys())}" + ) from exc + + def forward( + self, multivectors: torch.Tensor, scalars: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes f(x_0) * x for multivector x, where f is GELU, ReLU, or sigmoid. + + f is chosen depending on self.nonlinearity. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., self.in_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., self.in_channels, self.in_scalars) + Input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., self.out_channels, 16) + Output multivectors + output_scalars : torch.Tensor with shape (..., self.out_channels, self.in_scalars) + Output scalars + """ + + gates = multivectors[..., [0]] + outputs_mv = self.gated_nonlinearity(multivectors, gates=gates) + outputs_s = self.scalar_nonlinearity(scalars) + + return outputs_mv, outputs_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/nets/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/nets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7a87f16c013ed5b8018a4b9d51b53f9521f6b6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/nets/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .axial_gatr import AxialGATr +from .gatr import GATr diff --git a/gafl/build/geometric-algebra-transformer/gatr/nets/axial_gatr.py b/gafl/build/geometric-algebra-transformer/gatr/nets/axial_gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..fa76bd7e826e8e9422aeaa692fcaef16bf173f2a --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/nets/axial_gatr.py @@ -0,0 +1,253 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from dataclasses import replace +from typing import Optional, Tuple, Union + +import torch +from einops import rearrange +from torch import Tensor, nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.gatr_block import GATrBlock +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.tensors import construct_reference_multivector + +# Default rearrange patterns for odd blocks +_MV_REARRANGE_PATTERN = "... i j c x -> ... j i c x" +_S_REARRANGE_PATTERN = "... i j c -> ... j i c" + + +class AxialGATr(nn.Module): # pylint: disable=duplicate-code + """Axial GATr network for two token dimensions. + + This, together with gatr.nets.gatr.GATr, is the main architecture proposed in our paper. + + It combines `num_blocks` GATr transformer blocks, each consisting of geometric self-attention + layers, a geometric MLP, residual connections, and normalization layers. In addition, there + are initial and final equivariant linear layers. + + Assumes input data with shape `(..., num_items_1, num_items_2, num_channels, 16)`. + + The first, third, fifth, ... block computes attention over the `items_2` axis. The other blocks + compute attention over the `items_1` axis. Positional encoding can be specified separately for + both axes. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + hidden_mv_channels : int + Number of hidden multivector channels. + in_s_channels : None or int + If not None, sets the number of scalar input channels. + out_s_channels : None or int + If not None, sets the number of scalar output channels. + hidden_s_channels : None or int + If not None, sets the number of scalar hidden channels. + attention: Dict + Data for SelfAttentionConfig + mlp: Dict + Data for MLPConfig + num_blocks : int + Number of transformer blocks. + pos_encodings : tuple of bool + Whether to apply rotary positional embeddings along the item dimensions to the scalar keys + and queries. The first element in the tuple determines whether positional embeddings + are applied to the first item dimension, the second element the same for the second item + dimension. + collapse_dims : tuple of bool + Whether batch and token dimensions will be collapsed to support xformers block attention. + The first element of this tuple describes the behaviour in the 0th, 2nd, ... block, the + second element in the 1st, 3rd, ... block (where the axes are reversed). + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: int, + in_s_channels: Optional[int], + out_s_channels: Optional[int], + hidden_s_channels: Optional[int], + attention: SelfAttentionConfig, + mlp: MLPConfig, + num_blocks: int = 20, + checkpoint_blocks: bool = False, + pos_encodings: Tuple[bool, bool] = (False, False), + collapse_dims: Tuple[bool, bool] = (False, False), + **kwargs, + ) -> None: + super().__init__() + self.linear_in = EquiLinear( + in_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=hidden_s_channels, + ) + attention = SelfAttentionConfig.cast(attention) + mlp = MLPConfig.cast(mlp) + self.blocks = nn.ModuleList( + [ + GATrBlock( + mv_channels=hidden_mv_channels, + s_channels=hidden_s_channels, + attention=replace( + attention, + pos_encoding=pos_encodings[(block + 1) % 2], + ), + mlp=mlp, + ) + for block in range(num_blocks) + ] + ) + self.linear_out = EquiLinear( + hidden_mv_channels, + out_mv_channels, + in_s_channels=hidden_s_channels, + out_s_channels=out_s_channels, + ) + self._checkpoint_blocks = checkpoint_blocks + self._collapse_dims_for_even_blocks, self._collapse_dims_for_odd_blocks = collapse_dims + + def forward( + self, + multivectors: Tensor, + scalars: Optional[Tensor] = None, + attention_mask: Optional[Tuple] = None, + join_reference: Union[Tensor, str] = "data", + ) -> Tuple[Tensor, Optional[Tensor]]: + """Forward pass of the network. + + Parameters + ---------- + multivectors : Tensor with shape (..., num_items_1, num_items_2, in_mv_channels, 16) + Input multivectors. + scalars : None or Tensor with shape (..., num_items_1, num_items_2, in_s_channels) + Optional input scalars. + attention_mask : None or tuple of Tensor + Optional attention masks. + join_reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_1, num_items_2, out_mv_channels, 16) + Output multivectors. + outputs_s : None or Tensor with shape + (..., num_items_1, num_items_2, out_mv_channels, 16) + Output scalars, if scalars are provided. Otherwise None. + """ + + # Reference MV for equivariant join + reference_mv = construct_reference_multivector(join_reference, multivectors) + + # Pass through the blocks + h_mv, h_s = self.linear_in(multivectors, scalars=scalars) + for i, block in enumerate(self.blocks): + # For first, third, ... block, we want to perform attention over the first token + # dimension. We implement this by transposing the two item dimensions. + if i % 2 == 1: + h_mv, h_s, input_batch_dims = self._reshape_data_before_odd_blocks(h_mv, h_s) + else: + h_mv, h_s, input_batch_dims = self._reshape_data_before_even_blocks(h_mv, h_s) + + # Attention masks will also be different + if attention_mask is None: + this_attention_mask = None + else: + this_attention_mask = attention_mask[(i + 1) % 2] + + if self._checkpoint_blocks: + h_mv, h_s = checkpoint( + block, + h_mv, + use_reentrant=False, + scalars=h_s, + reference_mv=reference_mv, + attention_mask=this_attention_mask, + ) + else: + h_mv, h_s = block( + h_mv, + scalars=h_s, + reference_mv=reference_mv, + attention_mask=this_attention_mask, + ) + + # Transposing back to standard axis order + if i % 2 == 1: + h_mv, h_s = self._reshape_data_after_odd_blocks(h_mv, h_s, input_batch_dims) + else: + h_mv, h_s = self._reshape_data_after_even_blocks(h_mv, h_s, input_batch_dims) + + outputs_mv, outputs_s = self.linear_out(h_mv, scalars=h_s) + + return outputs_mv, outputs_s + + @staticmethod + def _construct_join_reference(inputs: Tensor): + """Constructs a reference vector for dualization from the inputs.""" + + # When using torch-geometric-style batching, this code should be adapted to perform the + # mean over the items in each batch, but not over the batch dimension. + # We leave this as an exercise for the practitioner :) + mean_dim = tuple(range(1, len(inputs.shape) - 1)) + return torch.mean(inputs, dim=mean_dim, keepdim=True) # (batch, 1, ..., 1, 16) + + def _reshape_data_before_odd_blocks(self, multivector, scalar): + # Transpose token axes + multivector = rearrange(multivector, _MV_REARRANGE_PATTERN) # (axis2, axis1, ...) + scalar = rearrange(scalar, _S_REARRANGE_PATTERN) # (axis2, axis1, ...) + + # Prepare uncollapsing + input_batch_dims = multivector.shape[:2] + assert scalar.shape[:2] == input_batch_dims + + # Collapse dimensions + if self._collapse_dims_for_odd_blocks: + multivector = multivector.reshape(-1, *multivector.shape[2:]) # (axis2 * axis1, ...) + scalar = scalar.reshape(-1, *scalar.shape[2:]) # (axis2 * axis1, ...) + + return multivector, scalar, input_batch_dims + + def _reshape_data_after_odd_blocks(self, multivector, scalar, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_odd_blocks: + multivector = multivector.reshape( + *input_batch_dims, *multivector.shape[1:] + ) # (axis2, axis1, ...) + scalar = scalar.reshape(*input_batch_dims, *scalar.shape[1:]) # (axis2, axis1, ...) + + # Re-transpose token axes + multivector = rearrange(multivector, _MV_REARRANGE_PATTERN) # (axis1, axis2, ...) + scalar = rearrange(scalar, _S_REARRANGE_PATTERN) # (axis1, axis2, ...) + + return multivector, scalar + + def _reshape_data_before_even_blocks(self, multivector, scalar): + # Prepare un-collapsing + input_batch_dims = multivector.shape[:2] + assert scalar.shape[:2] == input_batch_dims + + # Collapse + if self._collapse_dims_for_even_blocks: + multivector = multivector.reshape(-1, *multivector.shape[2:]) # (axis2 * axis1, ...) + scalar = scalar.reshape(-1, *scalar.shape[2:]) # (axis2 * axis1, ...) + + return multivector, scalar, input_batch_dims + + def _reshape_data_after_even_blocks(self, multivector, scalar, input_batch_dims): + # Uncollapse + if self._collapse_dims_for_even_blocks: + multivector = multivector.reshape( + *input_batch_dims, *multivector.shape[1:] + ) # (axis2, axis1, ...) + scalar = scalar.reshape(*input_batch_dims, *scalar.shape[1:]) # (axis2, axis1, ...) + + return multivector, scalar diff --git a/gafl/build/geometric-algebra-transformer/gatr/nets/gatr.py b/gafl/build/geometric-algebra-transformer/gatr/nets/gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc9381f4b8eecba7770f97f9ca88c574332562f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/nets/gatr.py @@ -0,0 +1,189 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Equivariant transformer for multivector data.""" + +from dataclasses import replace +from typing import Optional, Tuple, Union + +import torch +from torch import Tensor, nn +from torch.utils.checkpoint import checkpoint + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.gatr_block import GATrBlock +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.utils.tensors import construct_reference_multivector + + +class GATr(nn.Module): + """GATr network for a data with a single token dimension. + + This, together with gatr.nets.axial_gatr.AxialGATr, is the main architecture proposed in our + paper. + + It combines `num_blocks` GATr transformer blocks, each consisting of geometric self-attention + layers, a geometric MLP, residual connections, and normalization layers. In addition, there + are initial and final equivariant linear layers. + + Assumes input has shape `(..., items, in_channels, 16)`, output has shape + `(..., items, out_channels, 16)`, will create hidden representations with shape + `(..., items, hidden_channels, 16)`. + + Parameters + ---------- + in_mv_channels : int + Number of input multivector channels. + out_mv_channels : int + Number of output multivector channels. + hidden_mv_channels : int + Number of hidden multivector channels. + in_s_channels : None or int + If not None, sets the number of scalar input channels. + out_s_channels : None or int + If not None, sets the number of scalar output channels. + hidden_s_channels : None or int + If not None, sets the number of scalar hidden channels. + attention: Dict + Data for SelfAttentionConfig + mlp: Dict + Data for MLPConfig + num_blocks : int + Number of transformer blocks. + dropout_prob : float or None + Dropout probability + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + hidden_mv_channels: int, + in_s_channels: Optional[int], + out_s_channels: Optional[int], + hidden_s_channels: Optional[int], + attention: SelfAttentionConfig, + mlp: MLPConfig, + num_blocks: int = 10, + reinsert_mv_channels: Optional[Tuple[int]] = None, + reinsert_s_channels: Optional[Tuple[int]] = None, + checkpoint_blocks: bool = False, + dropout_prob: Optional[float] = None, + **kwargs, + ) -> None: + super().__init__() + self.linear_in = EquiLinear( + in_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=hidden_s_channels, + ) + attention = replace( + SelfAttentionConfig.cast(attention), # convert duck typing to actual class + additional_qk_mv_channels=0 + if reinsert_mv_channels is None + else len(reinsert_mv_channels), + additional_qk_s_channels=0 if reinsert_s_channels is None else len(reinsert_s_channels), + ) + mlp = MLPConfig.cast(mlp) + self.blocks = nn.ModuleList( + [ + GATrBlock( + mv_channels=hidden_mv_channels, + s_channels=hidden_s_channels, + attention=attention, + mlp=mlp, + dropout_prob=dropout_prob, + ) + for _ in range(num_blocks) + ] + ) + self.linear_out = EquiLinear( + hidden_mv_channels, + out_mv_channels, + in_s_channels=hidden_s_channels, + out_s_channels=out_s_channels, + ) + self._reinsert_s_channels = reinsert_s_channels + self._reinsert_mv_channels = reinsert_mv_channels + self._checkpoint_blocks = checkpoint_blocks + + def forward( + self, + multivectors: torch.Tensor, + scalars: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + join_reference: Union[Tensor, str] = "data", + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Forward pass of the network. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors. + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars. + attention_mask: None or torch.Tensor with shape (..., num_items, num_items) + Optional attention mask + join_reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors. + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + + # Reference multivector and channels that will be re-inserted in any query / key computation + reference_mv = construct_reference_multivector(join_reference, multivectors) + additional_qk_features_mv, additional_qk_features_s = self._construct_reinserted_channels( + multivectors, scalars + ) + + # Pass through the blocks + h_mv, h_s = self.linear_in(multivectors, scalars=scalars) + for block in self.blocks: + if self._checkpoint_blocks: + h_mv, h_s = checkpoint( + block, + h_mv, + use_reentrant=False, + scalars=h_s, + reference_mv=reference_mv, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + else: + h_mv, h_s = block( + h_mv, + scalars=h_s, + reference_mv=reference_mv, + additional_qk_features_mv=additional_qk_features_mv, + additional_qk_features_s=additional_qk_features_s, + attention_mask=attention_mask, + ) + + outputs_mv, outputs_s = self.linear_out(h_mv, scalars=h_s) + + return outputs_mv, outputs_s + + def _construct_reinserted_channels(self, multivectors, scalars): + """Constructs input features that will be reinserted in every attention layer.""" + + if self._reinsert_mv_channels is None: + additional_qk_features_mv = None + else: + additional_qk_features_mv = multivectors[..., self._reinsert_mv_channels, :] + + if self._reinsert_s_channels is None: + additional_qk_features_s = None + else: + assert scalars is not None + additional_qk_features_s = scalars[..., self._reinsert_s_channels] + + return additional_qk_features_mv, additional_qk_features_s diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cecd4e22ec689722aadf06c347081b6c60e054ec --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .attention import geometric_attention, pga_attention, sdp_attention +from .bilinear import geometric_product, outer_product +from .dropout import grade_dropout +from .dual import dual, equivariant_join +from .invariants import inner_product, norm, pin_invariants +from .linear import ( + NUM_PIN_LINEAR_BASIS_ELEMENTS, + equi_linear, + grade_involute, + grade_project, + reverse, +) +from .nonlinearities import gated_gelu, gated_gelu_divide, gated_relu, gated_sigmoid +from .normalization import equi_layer_norm diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/attention.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..0579a23330ef678ee6ea68400b2d775976f45eb1 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/attention.py @@ -0,0 +1,453 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import math +from functools import lru_cache +from typing import Callable, Optional, Tuple, Union + +import numpy as np +import torch +from einops import rearrange +from torch import Tensor +from torch.nn.functional import scaled_dot_product_attention as torch_sdpa +# from xformers.ops import AttentionBias, memory_efficient_attention + +from gatr.primitives.dual import join_norm +from gatr.primitives.invariants import inner_product +from gatr.utils.einsum import cached_einsum +from gatr.utils.tensors import expand_pairwise, to_nd + +# When computing the normalization factor in attention weights, multivectors contribute with the +# following factor: +_MV_SIZE_FACTOR = 8 + +# Multivector indices that contribute to inner product and trivectors +# All components that contribute to the inner product: +_INNER_PRODUCT_IDX = [0, 2, 3, 4, 8, 9, 10, 14] +# Scalar, non-ideal part of vector and bivector; no trivectors: +_INNER_PRODUCT_WO_TRI_IDX = [0, 2, 3, 4, 8, 9, 10] +# Trivector indices (ideal part first): +_TRIVECTOR_IDX = [11, 12, 13, 14] + +# Masked out attention logits are set to this constant (a finite replacement for -inf): +_MASKED_OUT = float("-inf") + +# Force the use of xformers attention, even when no xformers attention mask is provided: +# FORCE_XFORMERS = False + + +def sdp_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., num_items_in, num_s_channels_out) + Values, scalar part. + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_out, num_mv_channels_out, 16) + Result, multivector part + outputs_s : Tensor with shape (..., num_items_out, num_s_channels_out) + Result, scalar part + """ + + # Construct queries and keys by concatenating relevant MV components and aux scalars + q = torch.cat([rearrange(q_mv[..., _INNER_PRODUCT_IDX], "... c x -> ... (c x)"), q_s], -1) + k = torch.cat([rearrange(k_mv[..., _INNER_PRODUCT_IDX], "... c x -> ... (c x)"), k_s], -1) + + num_channels_out = v_mv.shape[-2] + v = torch.cat([rearrange(v_mv, "... c x -> ... (c x)"), v_s], -1) + + v_out = scaled_dot_product_attention(q, k, v) + + v_out_mv = rearrange(v_out[..., : num_channels_out * 16], "... (c x) -> ... c x", x=16) + v_out_s = v_out[..., num_channels_out * 16 :] + + return v_out_mv, v_out_s + + +def pga_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, + weights: Optional[Tuple[Tensor, Tensor, Tensor]] = None, + attention_mask=None, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products and the equivariant join. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + norm(join(q_mv[..., i, :, :], k_mv[..., j, :, :])) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Optionally, the three contributions are weighted with `weights`. + + This is not used in GATr, because it does not reduce to dot-product attention and thus does not + benefit from efficient implementations like `geometric_attention()` does. + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., num_items_in, num_s_channels_out) + Values, scalar part. + weights : None, or tuple of three Tensors + Weights for the combination of the inner product, join, and aux scalar parts + attention_mask: None or Tensor with shape (..., num_items, num_items) + Optional attention mask + + Returns + ------- + outputs_mv : Tensor with shape (..., num_items_out, num_mv_channels_out, 16) + Result, multivector part. + outputs_s : Tensor with shape (..., num_items_out, num_s_channels_out) + Result, scalar part. + """ + + # Negative weights are trouble + if weights is not None: + for weight in weights: + assert torch.min(weight) >= 0.0 + + # Compute attention weights, first through the inner product between multivectors... + q_mv = rearrange(q_mv, "... items_out channels x -> ... items_out 1 channels x") + k_mv = rearrange(k_mv, "... items_in channels x -> ... 1 items_in channels x") + h = inner_product(q_mv, k_mv)[..., 0] # (..., items_out, items_in, channels) + if weights is not None: + h = weights[0] * h + attn_weights = torch.sum(h, dim=-1) # (..., items_out, items_in) + + # ... then through the join... + h = -join_norm( + q_mv, k_mv, channel_sum=True, channel_weights=weights[1] if weights is not None else None + )[ + ..., 0 + ] # (..., items_out, items_in) + attn_weights = attn_weights + h + + # ... and finally from auxiliary scalars + q_s = rearrange(q_s, "... items_out channels -> ... items_out 1 channels") + k_s = rearrange(k_s, "... items_in channels -> ... 1 items_in channels") + h = q_s * k_s # (..., items_out, items_in, channels) + if weights is not None: + h = weights[2] * h + attn_weights = attn_weights + torch.sum(h, dim=-1) # (..., items_out, items_in) + + # Attention mask + if attention_mask is not None: + attn_weights.masked_fill_(~attention_mask, _MASKED_OUT) + + # Combine and weight + attn_weights = attn_weights / np.sqrt(2 * q_mv.shape[-2] * _MV_SIZE_FACTOR + q_s.shape[-1]) + + # Softmax + attn_weights = attn_weights.softmax(dim=-1) # Softmax over items_in + + # Compute attention output + outputs_mv = cached_einsum( + "... j i, ... i c x -> ... j c x", attn_weights, v_mv + ) # (..., items_out, channels, 16) + outputs_s = cached_einsum( + "... j i, ... i c -> ... j c", attn_weights, v_s + ) # (..., items_out, channels) + + return outputs_mv, outputs_s + + +@lru_cache() +def _build_dist_basis(device, dtype) -> Tuple[Tensor, Tensor]: + """Compute basis features for queries and keys in the geometric SDP attention. + + Parameters + ---------- + device: torch.device + Device. + dtype: torch.dtype + Dtype. + + Returns + ------- + basis_q : Tensor with shape (4, 4, 5) + Basis features for queries. + basis_k : Tensor with shape (4, 4, 5) + Basis features for keys. + """ + r3 = torch.arange(3, device=device) + basis_q = torch.zeros((4, 4, 5), device=device, dtype=dtype) + basis_k = torch.zeros((4, 4, 5), device=device, dtype=dtype) + + # -sum_i (q_i^2) * k_0^2 + basis_q[r3, r3, 0] = 1 + basis_k[3, 3, 0] = -1 + + # -q_0^2 * sum_i (k_i^2) + basis_q[3, 3, 1] = 1 + basis_k[r3, r3, 1] = -1 + + # sum_i 2 q_0 q_i k_0 k_i + basis_q[r3, 3, 2 + r3] = 1 + basis_k[r3, 3, 2 + r3] = 2 + + return basis_q, basis_k + + +def _build_dist_vec(tri: Tensor, basis: Tensor, normalizer: Callable[[Tensor], Tensor]) -> Tensor: + """Build 5D vector whose inner product with another such vector computes the squared distance. + + Parameters + ---------- + tri: Tensor + Batch of multivectors, only trivector part is used. + basis: Tensor + One of the bases from _build_dist_basis. + normalizer: Callable[[Tensor], Tensor] + A normalization function. + + Returns + ------- + outputs : Tensor + Batch of 5D vectors + """ + tri_normed = tri * normalizer(tri[..., [3]]) + vec = cached_einsum("xyz,... x,... y->... z", basis, tri_normed, tri_normed) + return vec + + +def lin_square_normalizer(v: Tensor, epsilon=0.001) -> Tensor: + """Apply linear square normalization to the input tensor. + + Parameters + ---------- + v : Tensor + Input tensor. + epsilon : float, optional + Small constant added to the denominator to avoid division by zero. + Default is 0.001. + + Returns + ------- + normalized_v : Tensor + Normalized tensor after applying linear square normalization. + """ + return v / (v.pow(2) + epsilon) + + +def geometric_attention( + q_mv: Tensor, + k_mv: Tensor, + v_mv: Tensor, + q_s: Tensor, + k_s: Tensor, + v_s: Tensor, + normalizer: Callable[[Tensor], Tensor], + weights: Optional[Tensor] = None, + attn_mask: Optional[Tensor] = None, +) -> Tuple[Tensor, Tensor]: + """Equivariant geometric attention based on scaled dot products and nonlinear aux features. + + This is the main attention mechanism used in GATr. Thanks to the nonlinear features, the + scaled-dot-product attention takes into account the Euclidean distance. + + Expects both multivector and scalar queries, keys, and values as inputs. + Then this function computes multivector and scalar outputs in the following way: + + ``` + attn_weights[..., i, j] = softmax_j[ + pga_inner_product(q_mv[..., i, :, :], k_mv[..., j, :, :]) + + euclidean_inner_product(q_s[..., i, :], k_s[..., j, :]) + + inner_product(phi(q_s[..., i, :]), psi(k_s[..., j, :])) + ] + out_mv[..., i, c, :] = sum_j attn_weights[..., i, j] v_mv[..., j, c, :] / norm + out_s[..., i, c] = sum_j attn_weights[..., i, j] v_s[..., j, c] / norm + ``` + + Optionally, the three contributions are weighted with `weights`. + + + Parameters + ---------- + q_mv : Tensor with shape (..., num_items_out, num_mv_channels_in, 16) + Queries, multivector part. + k_mv : Tensor with shape (..., num_items_in, num_mv_channels_in, 16) + Keys, multivector part. + v_mv : Tensor with shape (..., num_items_in, num_mv_channels_out, 16) + Values, multivector part. + q_s : Tensor with shape (..., heads, num_items_out, num_s_channels_in) + Queries, scalar part. + k_s : Tensor with shape (..., heads, num_items_in, num_s_channels_in) + Keys, scalar part. + v_s : Tensor with shape (..., heads, num_items_in, num_s_channels_out) + Values, scalar part. + normalizer : callable + Normalization function. + weights: Optional[Tensor] with shape (..., 1, num_channels_in) + Weights for the combination of the inner product, nonlinear distance-aware features, and + scalar parts. + attn_mask: Optional[Tensor] with shape (..., num_items_in, num_items_out) + Optional attention mask + + Returns + ------- + outputs_mv : Tensor with shape (..., heads, num_items_out, num_channels_out, 16) + Result, multivector part. + outputs_s : Tensor with shape (..., heads, num_items_out, num_s_channels_out) + Result, scalar part. + """ + bh_shape = q_mv.shape[:-3] + q_mv = to_nd(q_mv, 5) + k_mv = to_nd(k_mv, 5) + v_mv = to_nd(v_mv, 5) + q_s = to_nd(q_s, 4) + k_s = to_nd(k_s, 4) + v_s = to_nd(v_s, 4) + + num_mv_channels_v = v_mv.shape[-2] + num_s_channels_v = v_s.shape[-1] + num_mv_channels_qk = q_mv.shape[-2] + num_s_channels_qk = q_s.shape[-1] + + q_tri = q_mv[..., _TRIVECTOR_IDX] + k_tri = k_mv[..., _TRIVECTOR_IDX] + + basis_q, basis_k = _build_dist_basis(q_tri.device, q_tri.dtype) + + q_dist = _build_dist_vec(q_tri, basis_q, normalizer) + k_dist = _build_dist_vec(k_tri, basis_k, normalizer) + if weights is not None: + q_dist = q_dist * weights[..., None].to(q_dist.dtype) + + device = q_mv.device + dtype = q_mv.dtype + + num_channels_qk = num_mv_channels_qk * (7 + 5) + num_s_channels_qk + num_channels_v = num_mv_channels_v * 16 + num_s_channels_v + num_channels = max(num_channels_qk, num_channels_v) + num_channels = 8 * -(-num_channels // 8) # Ceil to multiple of 8 + + q = torch.cat( + [ + rearrange(q_mv[..., _INNER_PRODUCT_WO_TRI_IDX], "... c x -> ... (c x)"), + rearrange(q_dist, "... c d -> ... (c d)"), + q_s, + torch.zeros(*q_s.shape[:3], num_channels - num_channels_qk, device=device, dtype=dtype), + ], + -1, + ) + k = torch.cat( + [ + rearrange(k_mv[..., _INNER_PRODUCT_WO_TRI_IDX], "... c x -> ... (c x)"), + rearrange(k_dist, "... c d -> ... (c d)"), + k_s, + torch.zeros(*k_s.shape[:3], num_channels - num_channels_qk, device=device, dtype=dtype), + ], + -1, + ) + + v = torch.cat( + [ + rearrange(v_mv, "... c x -> ... (c x)"), + v_s, + torch.zeros(*v_s.shape[:3], num_channels - num_channels_v, device=device, dtype=dtype), + ], + -1, + ) + + k = k * math.sqrt(num_channels / num_channels_qk) # Correct for zero padding + q, k, v = expand_pairwise(q, k, v, exclude_dims=(-2,)) # Don't expand along token dimension + v_out = scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + + v_out_mv = rearrange(v_out[..., : num_mv_channels_v * 16], "... (c x) -> ... c x", x=16) + v_out_s = v_out[..., num_mv_channels_v * 16 : num_mv_channels_v * 16 + num_s_channels_v] + + v_out_mv = v_out_mv.view(*bh_shape, *v_out_mv.shape[-3:]) + v_out_s = v_out_s.view(*bh_shape, *v_out_s.shape[-2:]) + + return v_out_mv, v_out_s + + +def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + # attn_mask: Optional[Union[AttentionBias, Tensor]] = None, + attn_mask: Optional[Tensor] = None, +) -> Tensor: + """Execute (vanilla) scaled dot-product attention. + + Dynamically dispatch to xFormers if attn_mask is an instance of xformers.ops.AttentionBias + or FORCE_XFORMERS is set, use torch otherwise. + + Parameters + ---------- + query : Tensor + of shape [batch, head, item, d] + key : Tensor + of shape [batch, head, item, d] + value : Tensor + of shape [batch, head, item, d] + attn_mask : Optional[Union[AttentionBias, Tensor]] + Attention mask + + Returns + ------- + Tensor + of shape [batch, head, item, d] + """ + # if FORCE_XFORMERS or isinstance(attn_mask, AttentionBias): + # query = query.transpose(1, 2) # [batch, head, item, d] -> [batch, item, head, d] + # key = key.transpose(1, 2) + # value = value.transpose(1, 2) + # out = memory_efficient_attention( + # query.contiguous(), key.contiguous(), value, attn_bias=attn_mask + # ) + # out = out.transpose(1, 2) # [batch, item, head, d] -> [batch, head, item, d] + # return out + return torch_sdpa(query, key, value, attn_mask=attn_mask) diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/bilinear.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/bilinear.py new file mode 100644 index 0000000000000000000000000000000000000000..da42aedd1bc0700cd2f7fe346c979137e6795243 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/bilinear.py @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache +from pathlib import Path + +import torch + +from gatr.utils.einsum import cached_einsum + +_FILENAMES = {"gp": "geometric_product.pt", "outer": "outer_product.pt"} + + +@lru_cache() +def _load_bilinear_basis( + kind: str, device=torch.device("cpu"), dtype=torch.float32 +) -> torch.Tensor: + """Loads basis elements for Pin-equivariant bilinear maps between multivectors. + + This function is cached. + + Parameters + ---------- + kind : {"gp", "outer"} + Filename of the basis file, assumed to be found in __file__ / data + device : torch.Device or str + Device + dtype : torch.Dtype + Data type + + Returns + ------- + basis : torch.Tensor with shape (num_basis_elements, 16, 16, 16) + Basis elements for bilinear equivariant maps between multivectors. + """ + + # To avoid duplicate loading, base everything on float32 CPU version + if device not in [torch.device("cpu"), "cpu"] and dtype != torch.float32: + basis = _load_bilinear_basis(kind) + else: + filename = Path(__file__).parent.resolve() / "data" / _FILENAMES[kind] + sparse_basis = torch.load(filename).to(torch.float32) + # Convert to dense tensor + # The reason we do that is that einsum is not defined for sparse tensors + basis = sparse_basis.to_dense() + + return basis.to(device=device, dtype=dtype) + + +def geometric_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Computes the geometric product f(x,y) = xy. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x, y, and coeffs. + """ + + # Select kernel on correct device + gp = _load_bilinear_basis("gp", device=x.device, dtype=x.dtype) + + # Compute geometric product + outputs = cached_einsum("i j k, ... j, ... k -> ... i", gp, x, y) + + return outputs + + +def outer_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Computes the outer product `f(x,y) = x ^ y`. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x, y, and coeffs. + """ + + # Select kernel on correct device + op = _load_bilinear_basis("outer", device=x.device, dtype=x.dtype) + + # Compute geometric product + outputs = cached_einsum("i j k, ... j, ... k -> ... i", op, x, y) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/data/geometric_product.pt b/gafl/build/geometric-algebra-transformer/gatr/primitives/data/geometric_product.pt new file mode 100644 index 0000000000000000000000000000000000000000..902ee9d75eacab253dbbab54b406b563a9a88e99 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/data/geometric_product.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eb08e81346400f8081443b935b9cd38d9589fa89d522a7fe08a56ea9b6bce5f +size 5967 diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/data/outer_product.pt b/gafl/build/geometric-algebra-transformer/gatr/primitives/data/outer_product.pt new file mode 100644 index 0000000000000000000000000000000000000000..d805dec4c667b545deaba1d09edd828c37868802 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/data/outer_product.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a23738415b7ab0c5dbbd749a14e7a137f3f888e0869e0b01c882b9113781e8b +size 3135 diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/dropout.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..4b22d8f01daeeaf72b00195398b9bc35677985f7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/dropout.py @@ -0,0 +1,38 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.primitives.linear import grade_project + + +def grade_dropout(x: torch.Tensor, p: float, training: bool = True) -> torch.Tensor: + """Multivector dropout, dropping out grades independently. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input data. + p : float + Dropout probability (assumed the same for each grade). + training : bool + Switches between train-time and test-time behaviour. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Inputs with dropout applied. + """ + + # Project to grades + x = grade_project(x) + + # Apply standard 1D dropout + # For whatever reason, that only works with a single batch dimension, so let's reshape a bit + h = x.view(-1, 5, 16) + h = torch.nn.functional.dropout1d(h, p=p, training=training, inplace=False) + h = h.view(x.shape) + + # Combine grades again + h = torch.sum(h, dim=-2) + + return h diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/dual.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/dual.py new file mode 100644 index 0000000000000000000000000000000000000000..22a542cb2de831fa847fbe109f641348fc878cdd --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/dual.py @@ -0,0 +1,303 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache +from itertools import product +from typing import Tuple + +import torch + +from gatr.primitives.bilinear import outer_product +from gatr.utils.einsum import cached_einsum + +# Flag which reference join implementations we're using +_USE_EFFICIENT_JOIN = True + + +@lru_cache() +@torch.no_grad() +def _compute_dualization( + device=torch.device("cpu"), dtype=torch.float32 +) -> Tuple[torch.Tensor, torch.Tensor]: + """Constructs a tensor for the dual operation. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + permutation : list of int + Permutation index list to compute the dual + factors : torch.Tensor + Signs to multiply the dual outputs with. + """ + permutation = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + factors = torch.tensor( + [1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1], device=device, dtype=dtype + ) + return permutation, factors + + +@lru_cache() +@torch.no_grad() +def _compute_efficient_join(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a kernel for the join operation. + + The kernel is such that join(x, y)_i = einsum(kernel_ijk, x_j, x_k). + + For now, we do this in the simplest possible way: by computing the joins between two sets of + basis vectors. (Since the join is bilinear, that should be enough.) + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + kernel : torch.Tensor + Joint kernel + """ + + kernel = torch.zeros((16, 16, 16), dtype=dtype, device=device) + + for i in range(16): + for j in range(16): + x, y = torch.zeros(16, dtype=dtype, device=device), torch.zeros( + 16, dtype=dtype, device=device + ) + x[i] = 1.0 + y[j] = 1.0 + kernel[:, i, j] = dual(outer_product(dual(x), dual(y))) + + return kernel + + +@lru_cache() +@torch.no_grad() +def _compute_join_norm_idx(threshold=0.5) -> Tuple[list, list, list]: + """Constructs everything we need to compute norm(equi_norm(x,y)) in a memory-efficient way. + + Parameters + ---------- + threshold : float + Threshold that determines discretization of join kernel + + Returns + ------- + left_idx : list of list of int + List (output components) of list (contributing terms) of indices of x + left_idx : list of list of int + List (output components) of list (contributing terms) of indices of y + left_idx : list of list of float + List (output components) of list (contributing terms) of indices of y + """ + + # Get join kernel K_ijk + join_kernel = _compute_efficient_join() + + # Output components that contribute to the norm: all e_{i...k} without a 0 in the idx + output_idx = [0, 2, 3, 4, 8, 9, 10, 14] + + # Identify input idx that contribute to those output idx, with the corresponding signs + all_left_idx = [] + all_right_idx = [] + all_signs = [] + + for i in output_idx: + left_idx = [] + right_idx = [] + signs = [] + + for j, k in product(range(16), repeat=2): + if join_kernel[i, j, k] > threshold: + left_idx.append(j) + right_idx.append(k) + signs.append(1.0) + elif join_kernel[i, j, k] < -threshold: + left_idx.append(j) + right_idx.append(k) + signs.append(-1.0) + + all_left_idx.append(left_idx) + all_right_idx.append(right_idx) + all_signs.append(signs) + + return all_left_idx, all_right_idx, all_signs + + +def dual(x: torch.Tensor) -> torch.Tensor: + """Computes the dual of `inputs` (non-equivariant!). + + See Table 4 in the reference. + + References + ---------- + Leo Dorst, "A Guided Tour to the Plane-Based Geometric Algebra PGA", + https://geometricalgebra.org/downloads/PGA4CS.pdf + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector, of which we want to compute the dual. + + Returns + ------- + outputs : torch.Tensor with shale (..., 16) + The dual of `inputs`, using the pseudoscalar component of `reference` as basis. + """ + + # Select factors on correct device + perm, factors = _compute_dualization(x.device, x.dtype) + + # Compute dual + result = factors * x[..., perm] + + return result + + +def equivariant_join(x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor) -> torch.Tensor: + """Computes the equivariant join. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + This function uses either explicit_equivariant_join or efficient_equivariant_join, depending + on whether _USE_EFFICIENT_JOIN is set. + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Equivariant join result. + """ + + if _USE_EFFICIENT_JOIN: + return efficient_equivariant_join(x, y, reference) + + return explicit_equivariant_join(x, y, reference) + + +def explicit_equivariant_join( + x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor +) -> torch.Tensor: + """Computes the equivariant join, using the explicit, but slow, implementation. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Rquivariant join result. + """ + return reference[..., [14]] * dual(outer_product(dual(x), dual(y))) + + +def efficient_equivariant_join( + x: torch.Tensor, y: torch.Tensor, reference: torch.Tensor +) -> torch.Tensor: + """Computes the equivariant join, using the efficient implementation. + + ``` + equivariant_join(x, y; reference) = reference_123 * dual( dual(x) ^ dual(y) ) + ``` + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + reference : torch.Tensor + Reference multivector to break the orientation ambiguity. + + Returns + ------- + outputs : torch.Tensor + Rquivariant join result. + """ + + kernel = _compute_efficient_join(x.device, x.dtype) + return reference[..., [14]] * cached_einsum("i j k , ... j, ... k -> ... i", kernel, x, y) + + +def join_norm( + x: torch.Tensor, y: torch.Tensor, square=False, channel_sum=False, channel_weights=None +) -> torch.Tensor: + """Computes the norm of the join, `|join(x,y)|`, in a single operation. + + Optionally: + - computes the squared norm instead of the norm (when `square = True`), + - sums over channels, meaning the second-to-last dimension (when `channel_sum = True`) + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Left input + y : torch.Tensor with shape (..., 16) + Right input + square : bool + If True, computes the squared norm rather than the norm + channel_sum : bool + If True, sums the result over channels (before taking the square root). We assume channels + correspond to the second-to-last dimension of the input tensors. + channel_weights : None torch.Tensor with shape (..., num_channels) + If channel_sum is True, a non-None value of channel_weights weighs the different channels + before summing over them. (Note that we do not perform any normalization here.) + + Returns + ------- + norm : torch.Tensor with shape (..., 1) + Norm of join + """ + + # Prepare computation + output = 0.0 + all_left_idx, all_right_idx, all_signs = _compute_join_norm_idx() + + # Sum over all contributing terms + for left_idx, right_idx, signs in zip(all_left_idx, all_right_idx, all_signs): + # Compute contribution + component = 0.0 + for j, k, sign in zip(left_idx, right_idx, signs): + component = component + sign * x[..., j] * y[..., k] + component = component**2 + + # Compute channel sum if desired + if channel_sum: + if channel_weights is not None: + component = component * channel_weights + component = component.sum(dim=-1) + + output = output + component + + # Square root, unless the square norm is computed + if not square: + output = torch.sqrt(output) + + return output.unsqueeze(-1) diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/invariants.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/invariants.py new file mode 100644 index 0000000000000000000000000000000000000000..70a25fcd8e31121554cbf6c8d8df132c92533d51 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/invariants.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import torch +import torch.linalg + +from gatr.primitives.bilinear import _load_bilinear_basis +from gatr.primitives.linear import _compute_reversal, grade_project +from gatr.utils.einsum import cached_einsum + + +@lru_cache() +def compute_inner_product_mask(device=torch.device("cpu")) -> torch.Tensor: + """Constructs a bool array for the inner product calculation. + + The inner product of MVs is <~x y>_0, i.e. take the grade-0 component of the geometric + product of the reverse of x with y. + Both the scalar component of the GP, and the reversal matrix, are diagonal. + Their product is 0 for basis elements involving e0, and 1 elsewhere, i.e. + IP = [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0] + for dim order '', 'e0', 'e1', 'e2', 'e3', 'e01', 'e02', 'e03', 'e12', 'e13', 'e23', + 'e012', 'e013', 'e023', 'e123', 'e0123' + + Parameters + ---------- + device : torch.device + Device + + Returns + ------- + ip_mask : torch.Tensor with shape (16,) + Inner product mask + """ + gp = _load_bilinear_basis("gp", device=device, dtype=torch.float32) + inner_product_mask = torch.diag(gp[0]) * _compute_reversal(device=device, dtype=torch.float32) + return inner_product_mask.bool() + +def inner_product(x: torch.Tensor, y: torch.Tensor, channel_sum: bool = False) -> torch.Tensor: + """Computes the inner product of multivectors f(x,y) = = <~x y>_0. + + In addition to summing over the 16 multivector dimensions, this function also sums + over an additional channel dimension if channel_sum == True. + + Equal to `geometric_product(reverse(x), y)[..., [0]]` (but faster). + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) or (..., channels, 16) + First input multivector. Batch dimensions must be broadcastable between x and y. + y : torch.Tensor with shape (..., 16) or (..., channels, 16) + Second input multivector. Batch dimensions must be broadcastable between x and y. + channel_sum: bool + Whether to sum over the second-to-last axis (channels) + + Returns + ------- + outputs : torch.Tensor with shape (..., 1) + Result. Batch dimensions are result of broadcasting between x and y. + """ + + x = x[..., compute_inner_product_mask(device=x.device)] + y = y[..., compute_inner_product_mask(device=x.device)] + + if channel_sum: + outputs = cached_einsum("... c i, ... c i -> ...", x, y) + else: + outputs = cached_einsum("... i, ... i -> ...", x, y) + + # We want the output to have shape (..., 1) + outputs = outputs.unsqueeze(-1) + + return outputs + + +def norm(x: torch.Tensor) -> torch.Tensor: + """Computes the GA norm of an input multivector. + + Equal to sqrt(inner_product(x, x)). + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 1) + Geometric algebra norm of x. + """ + return torch.linalg.norm(x[..., compute_inner_product_mask(device=x.device)], dim=-1, keepdim=True) # torch.linalg.norm is faster than the einsum version below + # return torch.sqrt(torch.clamp(inner_product(x, x), 0.0)) + +def pin_invariants(x: torch.Tensor) -> torch.Tensor: + """Computes five invariants from multivectors: scalar component, norms of the four other grades. + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 5) + Invariants computed from input multivectors + """ + + # Project to grades + projections = grade_project(x) # (..., 5, 16) + + # Compute norms + squared_norms = inner_product(projections, projections)[..., 0] # (..., 5) + norms = torch.sqrt(torch.clamp(squared_norms, 0.0)) + + # Outputs: scalar component of input and norms of four other grades + return torch.cat((x[..., [0]], norms[..., 1:]), dim=-1) # (..., 5) diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/linear.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a50df0bf0f9e9e324008833333f720df1d3b1b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/linear.py @@ -0,0 +1,201 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import torch + +from gatr.utils.einsum import cached_einsum, custom_einsum + + +@lru_cache() +def _compute_pin_equi_linear_basis( + device=torch.device("cpu"), dtype=torch.float32, normalize=True +) -> torch.Tensor: + """Constructs basis elements for Pin(3,0,1)-equivariant linear maps between multivectors. + + This function is cached. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + normalize : bool + Whether to normalize the basis elements + + Returns + ------- + basis : torch.Tensor with shape (7, 16, 16) + Basis elements for equivariant linear maps. + """ + + # We constructed these manually in a notebook, here hardcoded for convenience + basis_elements = [ + [0], + [1, 2, 3, 4], + [5, 6, 7, 8, 9, 10], + [11, 12, 13, 14], + [15], + [(1, 0)], + [(5, 2), (6, 3), (7, 4)], + [(11, 8), (12, 9), (13, 10)], + [(15, 14)], + ] + basis = [] + + for elements in basis_elements: + w = torch.zeros((16, 16)) + for element in elements: + try: + i, j = element + w[i, j] = 1.0 + except TypeError: + w[element, element] = 1.0 + + if normalize: + w /= torch.linalg.norm(w) + + w = w.unsqueeze(0) + basis.append(w) + + catted_basis = torch.cat(basis, dim=0) + + return catted_basis.to(device=device, dtype=dtype) + + +@lru_cache() +def _compute_reversal(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a matrix that computes multivector reversal. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + reversal_diag : torch.Tensor with shape (16,) + The diagonal of the reversal matrix, consisting of +1 and -1 entries. + """ + reversal_flat = torch.ones(16, device=device, dtype=dtype) + reversal_flat[5:15] = -1 + return reversal_flat + + +@lru_cache() +def _compute_grade_involution(device=torch.device("cpu"), dtype=torch.float32) -> torch.Tensor: + """Constructs a matrix that computes multivector grade involution. + + Parameters + ---------- + device : torch.device + Device + dtype : torch.dtype + Dtype + + Returns + ------- + involution_diag : torch.Tensor with shape (16,) + The diagonal of the involution matrix, consisting of +1 and -1 entries. + """ + involution_flat = torch.ones(16, device=device, dtype=dtype) + involution_flat[1:5] = -1 + involution_flat[11:15] = -1 + return involution_flat + + +NUM_PIN_LINEAR_BASIS_ELEMENTS = len(_compute_pin_equi_linear_basis()) + + +def equi_linear(x: torch.Tensor, coeffs: torch.Tensor) -> torch.Tensor: + """Pin-equivariant linear map f(x) = sum_{a,j} coeffs_a W^a_ij x_j. + + The W^a are seven pre-defined basis elements. + + Parameters + ---------- + x : torch.Tensor with shape (..., in_channels, 16) + Input multivector. Batch dimensions must be broadcastable between x and coeffs. + coeffs : torch.Tensor with shape (out_channels, in_channels, 7) + Coefficients for the 59 basis elements. Batch dimensions must be broadcastable between x and + coeffs. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Result. Batch dimensions are result of broadcasting between x and coeffs. + """ + basis = _compute_pin_equi_linear_basis(device=x.device, dtype=x.dtype) + # return custom_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x, path=[0, 1, 0, 1]) + return cached_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x) + +def grade_project(x: torch.Tensor) -> torch.Tensor: + """Projects an input tensor to the individual grades. + + The return value is a single tensor with a new grade dimension. + + NOTE: this primitive is not used widely in our architectures. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 5, 16) + Output multivector. The second-to-last dimension indexes the grades. + """ + + # Select kernel on correct device + basis = _compute_pin_equi_linear_basis(device=x.device, dtype=x.dtype, normalize=False) + + # First five basis elements are grade projections + basis = basis[:5] + + # Project to grades + projections = cached_einsum("g i j, ... j -> ... g i", basis, x) + + return projections + + +def reverse(x: torch.Tensor) -> torch.Tensor: + """Computes the reversal of a multivector. + + The reversal has the same scalar, vector, and pseudoscalar components, but flips sign in the + bivector and trivector components. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivector. + """ + return _compute_reversal(device=x.device, dtype=x.dtype) * x + + +def grade_involute(x: torch.Tensor) -> torch.Tensor: + """Computes the grade involution of a multivector. + + The reversal has the same scalar, bivector, and pseudoscalar components, but flips sign in the + vector and trivector components. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Input multivector. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Output multivector. + """ + + return _compute_grade_involution(device=x.device, dtype=x.dtype) * x diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/nonlinearities.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3a4c43eae9ff40b7d1754f592220f9482e9a74 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/nonlinearities.py @@ -0,0 +1,111 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import math + +import torch + +_GATED_GELU_DIV_FACTOR = math.sqrt(2 / math.pi) * 2 + + +def gated_relu(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated ReLU nonlinearity. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + ReLU(gates) * x. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes ReLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.relu(gates) + outputs = weights * x + return outputs + + +def gated_sigmoid(x: torch.Tensor, gates: torch.Tensor): + """Pin-equivariant gated sigmoid nonlinearity. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + sigmoid(gates) * x. + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes sigmoid(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.sigmoid(gates) + outputs = weights * x + return outputs + + +def gated_gelu(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated GeLU nonlinearity without division. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + GeLU(gates) * x. + + References + ---------- + Dan Hendrycks, Kevin Gimpel, "Gaussian Error Linear Units (GELUs)", arXiv:1606.08415 + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes GeLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.nn.functional.gelu(gates, approximate="tanh") + outputs = weights * x + return outputs + + +def gated_gelu_divide(x: torch.Tensor, gates: torch.Tensor) -> torch.Tensor: + """Pin-equivariant gated GeLU nonlinearity with division. + + Given multivector input x and scalar input gates (with matching batch dimensions), computes + GeLU(gates) * x / gates. + + References + ---------- + Dan Hendrycks, Kevin Gimpel, "Gaussian Error Linear Units (GELUs)", arXiv:1606.08415 + + Parameters + ---------- + x : torch.Tensor with shape (..., 16) + Multivector input + gates : torch.Tensor with shape (..., 1) + Pin-invariant gates. + + Returns + ------- + outputs : torch.Tensor with shape (..., 16) + Computes GeLU(gates) * x, with broadcasting along the last dimension. + """ + + weights = torch.sigmoid(_GATED_GELU_DIV_FACTOR * (gates + 0.044715 * gates**3)) + outputs = weights * x + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/primitives/normalization.py b/gafl/build/geometric-algebra-transformer/gatr/primitives/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..2da0b51e07850dd3a1313d5873665b321342a2e7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/primitives/normalization.py @@ -0,0 +1,49 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.primitives.invariants import inner_product + + +def equi_layer_norm( + x: torch.Tensor, channel_dim: int = -2, gain: float = 1.0, epsilon: float = 0.01 +) -> torch.Tensor: + """Equivariant LayerNorm for multivectors. + + Rescales input such that `mean_channels |inputs|^2 = 1`, where the norm is the GA norm and the + mean goes over the channel dimensions. + + Using a factor `gain > 1` makes up for the fact that the GP norm overestimates the actual + standard deviation of the input data. + + Parameters + ---------- + x : torch.Tensor with shape `(batch_dim, *channel_dims, 16)` + Input multivectors. + channel_dim : int + Channel dimension index. Defaults to the second-last entry (last are the multivector + components). + gain : float + Target output scale. + epsilon : float + Small numerical factor to avoid instabilities. By default, we use a reasonably large number + to balance issues that arise from some multivector components not contributing to the norm. + + Returns + ------- + outputs : torch.Tensor with shape `(batch_dim, *channel_dims, 16)` + Normalized inputs. + """ + + # Compute mean_channels |inputs|^2 + squared_norms = inner_product(x, x) + squared_norms = torch.mean(squared_norms, dim=channel_dim, keepdim=True) + + # Insure against low-norm tensors (which can arise even when `x.var(dim=-1)` is high b/c some + # entries don't contribute to the inner product / GP norm!) + squared_norms = torch.clamp(squared_norms, epsilon) + + # Rescale inputs + outputs = gain * x / torch.sqrt(squared_norms) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/__init__.py b/gafl/build/geometric-algebra-transformer/gatr/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/clifford.py b/gafl/build/geometric-algebra-transformer/gatr/utils/clifford.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bf4792dee4d6bd12bf944ff1b45b48971402da --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/clifford.py @@ -0,0 +1,130 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Geometric algebra operations based on the clifford library.""" + +from typing import Optional + +import clifford +import numpy as np +import torch +from clifford import pga as PGA + + +def np_to_mv(array): + """Shorthand to transform a numpy array to a PGA multivector.""" + return clifford.MultiVector(PGA.layout, value=array) + + +def tensor_to_mv(tensor): + """Shorthand to transform a numpy array to a PGA multivector.""" + return np_to_mv(tensor.detach().cpu().numpy()) + + +def tensor_to_mv_list(tensor): + """Transforms a torch.Tensor to a list of multivector objects.""" + + tensor = tensor.reshape((-1, 16)) + mv_list = [tensor_to_mv(x) for x in tensor] + + return mv_list + + +def mv_list_to_tensor(multivectors, batch_shape=None): + """Transforms a list of multivector objects to a torch.Tensor.""" + + tensor = torch.from_numpy(np.array([mv.value for mv in multivectors])).to(torch.float32) + if batch_shape is not None: + tensor = tensor.reshape(*batch_shape, 16) + + return tensor + + +def sample_pin_multivector(spin: bool = False, rng: Optional[np.random.Generator] = None): + """Samples from the Pin(3,0,1) group as a product of reflections.""" + + if rng is None: + rng = np.random.default_rng() + + # Sample number of reflections we want to multiply + if spin: + i = np.random.randint(3) * 2 + else: + i = np.random.randint(5) + + # If no reflections, just return unit scalar + if i == 0: + return PGA.blades[""] + + multivector = 1.0 + for _ in range(i): + # Sample reflection vector + vector = np.zeros(16) + vector[1:5] = rng.normal(size=4) + vector_mv = np_to_mv(vector) + vector_mv = vector_mv / vector_mv.mag2() ** 0.5 + + # Multiply together (geometric product) + multivector = multivector * vector_mv + + return multivector + + +def get_parity(mv): + """Gets parity of a clifford multivector. + + Given a clifford multivector, returns True if it is pure-odd-grade, False if it is pure-even + grade, and raises a RuntimeError if it is mixed. + """ + if mv == mv.even: + return False + if mv == mv.odd: + return True + raise RuntimeError(f"Mixed-grade multivector: {mv}") + + +def sandwich(u, x): + """Given clifford multivectors, computes their sandwich product. + + Specifically, given a Pin element u and a PGA element x, both given as clifford multivectors, + computes the sandwich product + ``` + sandwich(x, u) = (-1)^(grade(u) * grade(x)) u x u^{-1} . + ``` + + If `u` is of odd grades, then this is equal to `u * grade_involute(x) * u^{-1}`. + If `u` is of even grades, then this is equal to `u * x * u^{-1}`. + """ + + if get_parity(u): + return u * x.gradeInvol() * u.shirokov_inverse() + + return u * x * u.shirokov_inverse() + + +class SlowRandomPinTransform: + """Random Pin transform on a multivector torch.Tensor. + + Slow, only used for testing purposes. Breaks computational graph. + """ + + def __init__(self, spin=False, rng=None): + super().__init__() + self._u = sample_pin_multivector(spin, rng) + self._u_inverse = self._u.shirokov_inverse() + + def __call__(self, inputs: torch.Tensor) -> torch.Tensor: + """Apply Pin transformation to multivector inputs.""" + # Input shape + assert inputs.shape[-1] == 16 + batch_dims = inputs.shape[:-1] + + # Convert inputs to list of multivectors + inputs_mv = tensor_to_mv_list(inputs) + + # Transform + outputs_mv = [sandwich(self._u, x) for x in inputs_mv] + + # Back to tensor + outputs = mv_list_to_tensor(outputs_mv, batch_shape=batch_dims) + + return outputs diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/compile_linear.py b/gafl/build/geometric-algebra-transformer/gatr/utils/compile_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..3db8ac0f70b051cbaa87b47006abf6dd6f4e1748 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/compile_linear.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# Copyright (c) 2024 Qualcomm Technologies, Inc. +# All rights reserved. + +from typing import Optional, Tuple, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from gatr.layers.linear import EquiLinear +from gatr.primitives.linear import _compute_pin_equi_linear_basis + + +class CompiledLinear(nn.Module): + """A drop-in replacement for EquiLinear for fast inference. + + Not trainable. Parameters must be set by hand. + + Parameters + ---------- + in_mv_channels : int + Input multivector channels + out_mv_channels : int + Output multivector channels + bias : bool + Whether a bias term is added to the scalar component of the multivector outputs + in_s_channels : int or None + Input scalar channels. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + """ + + def __init__( + self, + in_mv_channels: int, + out_mv_channels: int, + in_s_channels: Optional[int] = None, + out_s_channels: Optional[int] = None, + bias: bool = True, + ) -> None: + super().__init__() + in_channels = 16 * in_mv_channels + (in_s_channels or 0) + out_channels = 16 * out_mv_channels + (out_s_channels or 0) + self.register_buffer("weight", torch.zeros(out_channels, in_channels)) + self.register_buffer("bias", torch.zeros(out_channels) if bias else None) + self._out_mv_channels = out_mv_channels + self._out_s_channels = out_s_channels + + def forward( + self, multivectors: torch.Tensor, scalars: Optional[torch.Tensor] = None + ) -> Tuple[torch.Tensor, Union[torch.Tensor, None]]: + """Compute compiled linear map. + + Parameters + ---------- + multivectors : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors + scalars : None or torch.Tensor with shape (..., in_s_channels) + Optional input scalars + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., out_mv_channels, 16) + Output multivectors + outputs_s : None or torch.Tensor with shape (..., out_s_channels) + Output scalars, if scalars are provided. Otherwise None. + """ + b = multivectors.shape[:-2] + inputs = multivectors.view(*b, -1) + if scalars is not None: + inputs = torch.cat([inputs, scalars], -1) + outputs = F.linear(inputs, self.weight, self.bias) # pylint: disable=not-callable + outputs_mv = outputs[..., : 16 * self._out_mv_channels].view(*b, -1, 16) + if self._out_s_channels is None: + outputs_s = None + else: + outputs_s = outputs[..., 16 * self._out_mv_channels :] + + return outputs_mv, outputs_s + + +def compile_equi_linear(equi_linear: EquiLinear) -> CompiledLinear: + """Transform EquiLinear module to equivalent CompiledLinear module. + + Used for fast inference, not trainable! + + Parameters + ---------- + equi_linear : EquiLinear + + Returns + ------- + CompiledLinear + """ + # Figure out hyperparameters of EquiLinear from parameter shapes + out_mv_channels, in_mv_channels, _ = equi_linear.weight.shape + in_s_channels = equi_linear.s2mvs.weight.shape[1] if equi_linear.s2mvs else None + out_s_channels = equi_linear.mvs2s.weight.shape[0] if equi_linear.mvs2s else None + if in_s_channels is None: + bias = equi_linear.bias is not None + else: + bias = equi_linear.s2mvs.bias is not None + + compiled = CompiledLinear( + in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias=bias + ) + compiled.to(device=equi_linear.weight.device, dtype=equi_linear.weight.dtype) + + # The number of channels the multivectors occupy + offset_in = in_mv_channels * 16 + offset_out = out_mv_channels * 16 + + # Materialize the equivariant maps by linearly combining the basis maps + basis = _compute_pin_equi_linear_basis( + device=equi_linear.weight.device, dtype=equi_linear.weight.dtype + ) + mv_mv_weight = torch.einsum("y x a, a i j -> y i x j", equi_linear.weight, basis) + compiled.weight[:offset_out, :offset_in] = mv_mv_weight.reshape(offset_out, offset_in) + + if in_s_channels: + compiled.weight[:offset_out:16, offset_in:] = equi_linear.s2mvs.weight + if out_s_channels: + compiled.weight[offset_out:, :offset_in:16] = equi_linear.mvs2s.weight + if in_s_channels and out_s_channels: + compiled.weight[offset_out:, offset_in:] = equi_linear.s2s.weight + + if bias: + if equi_linear.bias is not None: + compiled.bias[:offset_out:16] = equi_linear.bias.flatten() + elif equi_linear.s2mvs.bias is not None: + compiled.bias[:offset_out:16] = equi_linear.s2mvs.bias + if out_s_channels: + compiled.bias[offset_out:] = equi_linear.mvs2s.bias + + return compiled + + +def compile_equi_linear_submodules(model: nn.Module): + """Replace all EquiLinear submodules in module with compiled version. + + Parameters + ---------- + model : nn.Module + Model whose EquiLinear submodules will be replaced. Argument mutated! + """ + + def walker(module): + for name, submodule in module.named_children(): + if isinstance(submodule, EquiLinear): + compiled_linear = compile_equi_linear(submodule) + setattr(module, name, compiled_linear) + + model.apply(walker) diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/dual_basis.py b/gafl/build/geometric-algebra-transformer/gatr/utils/dual_basis.py new file mode 100644 index 0000000000000000000000000000000000000000..e33f9a46398a780863b61d09c0dbb9a83ff29473 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/dual_basis.py @@ -0,0 +1,70 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from functools import lru_cache + +import numpy as np +import torch +from clifford import pga as PGA +from clifford.pga import layout + +e1, e2, e3, e123 = PGA.blades["e1"], PGA.blades["e2"], PGA.blades["e3"], PGA.blades["e123"] + + +def point_r3_to_mv(v): + """Helper function to construct basis for reference_dual().""" + return e123 + sum(v * [e1.dual(), e2.dual(), e3.dual()]) + + +def point_r3_expand(p_r3): + """Helper function to construct basis for reference_dual().""" + p_sq = np.einsum("...i,...j->...ij", p_r3, p_r3).reshape(*p_r3.shape[:-1], 9) + p_exp = np.concatenate([p_sq, p_r3, np.ones((*p_r3.shape[:-1], 1))], -1) + return p_exp + + +def sw(u, x): + """Helper function to construct basis for reference_dual().""" + grades = set(g % 2 for g in u.grades()) + assert len(grades) == 1, f"{u} is mixed odd/even" + if grades.pop() == 0: + return u * x * u.shirokov_inverse() + return u * x.gradeInvol() * u.shirokov_inverse() + + +def dual(p, x): + """Helper function to construct basis for reference_dual().""" + p = p(3) # Take the trivector of p, making it a point + s = p | -e123 # The scale to make it a proper point + p = p / s # Normalize so that e123 dim is 1 + t = 0.5 - (e123 * p) / 2 # Translation from p to origin + assert sw(t, p) == e123 # Assert this works + x_t = sw(t, x) # Move x to origin + y = x_t.dual() # Dualize at origin + y_t = sw(t.inv(), y) # Move back to p + return y_t * s # Re-apply scale of p + + +def compute_dual_basis(): + """Helper function to construct basis for reference_dual().""" + num_points = 100 + p_r3 = np.random.rand(num_points, 3) + p_mv = [point_r3_to_mv(v) for v in p_r3] + p_exp = point_r3_expand(p_r3) + ws = [] + for i in range(16): + x = layout.MultiVector(np.eye(16)[i]) + ys = np.stack([dual(p, x).value for p in p_mv]) + w = (np.linalg.pinv(p_exp) @ ys).T + ws.append(w) + w = np.stack(ws, 1) + w_rounded = (w * 2).round() / 2 # Round to halves + np.testing.assert_allclose(w, w_rounded, atol=1e-10) + w = w_rounded + return w + + +@lru_cache(5) +def compute_dual_basis_torch(device): + """Helper function to construct basis for reference_dual().""" + w = compute_dual_basis() + return torch.tensor(w, dtype=torch.float32, device=device) diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/einsum.py b/gafl/build/geometric-algebra-transformer/gatr/utils/einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..63de78511d387c4c6651ecb23925796996917004 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/einsum.py @@ -0,0 +1,40 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""This module provides efficiency improvements over torch's einsum through caching.""" + +import functools +from typing import List, Sequence + +import opt_einsum +import torch + + +def custom_einsum(equation: str, *operands: torch.Tensor, path: List[int]) -> torch.Tensor: + """Computes einsum with a custom contraction order.""" + + # Justification: For the sake of performance, we need direct access to torch's private methods. + + # pylint:disable-next=protected-access + return torch._VF.einsum(equation, operands, path=path) # type: ignore[attr-defined] + + +def cached_einsum(equation: str, *operands: torch.Tensor) -> torch.Tensor: + """Computes einsum with a cached optimal contraction. + + Inspired by upstream + https://github.com/pytorch/pytorch/blob/v1.13.0/torch/functional.py#L381. + """ + op_shape = tuple(op.shape for op in operands) + path = _get_cached_path_for_equation_and_shapes(equation=equation, op_shape=op_shape) + + return custom_einsum(equation, *operands, path=path) + + +@functools.lru_cache(maxsize=None) +def _get_cached_path_for_equation_and_shapes( + equation: str, op_shape: Sequence[torch.Tensor] +) -> List[int]: + """Provides caching of optimal path.""" + tupled_path = opt_einsum.contract_path(equation, *op_shape, optimize="optimal", shapes=True)[0] + + return [item for pair in tupled_path for item in pair] diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/logger.py b/gafl/build/geometric-algebra-transformer/gatr/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d7956515b74038f084796eaab69708cfae4951 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/logger.py @@ -0,0 +1,6 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import logging + +logger = logging.getLogger("gatr_experiment") +logging_initialized = False diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/misc.py b/gafl/build/geometric-algebra-transformer/gatr/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..1f34aa24e38e52b83824a8bf7a9f539cc3fc96b5 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/misc.py @@ -0,0 +1,146 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from collections.abc import Mapping +from functools import lru_cache +from itertools import product + +import numpy as np +import torch + + +class NaNError(BaseException): + """Exception to be raise when the training encounters a NaN in loss or model weights.""" + + +def get_device() -> torch.device: + """Gets CUDA if available, CPU else.""" + return torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") + + +def frequency_check(step, every_n_steps, skip_initial=False, include_fractional=None): + """Checks whether an action should be performed at a given step and frequency. + + If `include_fractional` is given, the check also returns True when + `step == round(every_n_steps * fraction)` for each `fraction` in `include_fractional`. + + Parameters + ---------- + step : int + Step number (one-indexed) + every_n_steps : None or int + Desired action frequency. None or 0 correspond to never executing the action. + skip_initial : bool + If True, frequency_check returns False at step 0. + include_fractional : None or tuple of float + If not None, the check also returns True when `step == round(every_n_steps * fraction)` + for each `fraction` in `include_fractional`. + + Returns + ------- + decision : bool + Whether the action should be executed. + """ + + if every_n_steps is None or every_n_steps == 0: + return False + + if skip_initial and step == 0: + return False + + if include_fractional is not None: + for fraction in include_fractional: + if step == int(round(fraction * every_n_steps)): + return True + + return step % every_n_steps == 0 + + +def flatten_dict(d, parent_key="", sep="."): + """Flattens a nested dictionary with str keys.""" + items = [] + for k, v in d.items(): + new_key = parent_key + sep + k if parent_key else k + if isinstance(v, Mapping): + items.extend(flatten_dict(v, new_key, sep=sep).items()) + else: + items.append((new_key, v)) + return dict(items) + + +def sample_uniform_in_circle(n, min_radius=0.0, max_radius=1.0): + """Samples uniformly in a 2D circle using batched rejection sampling.""" + + assert 0.0 <= min_radius < max_radius, "Inconsistent inputs to sample_uniform_in_circle" + + mask = None + samples = None + + while samples is None or np.sum(mask) > 0: + new_samples = max_radius * np.random.uniform(low=-1, high=1, size=(n, 2)) + + if samples is None: + samples = new_samples + else: + samples = (1 - mask) * samples + mask * new_samples + + r2 = np.sum(samples**2, axis=-1) + mask = np.logical_or((r2 < min_radius**2), (r2 > max_radius**2))[:, np.newaxis] + + return samples + + +def sample_log_uniform(min_, max_, size): + """Samples log-uniformly from (min_, max_).""" + if isinstance(size, tuple): + n = int(np.product(size)) + else: + n = size + + log_x = np.random.rand(n) * (np.log(max_) - np.log(min_)) + np.log(min_) + x = np.exp(log_x) + + if isinstance(size, tuple): + x = x.reshape(size) + + return x + + +@lru_cache() +@torch.no_grad() +def make_full_edge_index(num_nodes, batchsize=1, self_loops=False, device=torch.device("cpu")): + """Creates a PyG-style edge index for a fully connected graph of `num_nodes` nodes.""" + + # Construct fully connected edge index + src, dst = [], [] + for i, j in product(range(num_nodes), repeat=2): + if not self_loops and i == j: + continue + src.append(i) + dst.append(j) + + edge_index_per_batch = torch.LongTensor([src, dst]).to(device) + + # Repeat for each batch element + if batchsize > 1: + edge_index_list = [edge_index_per_batch + k * num_nodes for k in range(batchsize)] + edge_index = torch.cat(edge_index_list, dim=1) + else: + edge_index = edge_index_per_batch + + return edge_index + + +def get_batchsize(data): + """Given either a tensor or a list of tensors or a dict of tensors, returns the batchsize.""" + + if isinstance(data, Mapping): + assert len(data) > 0 + data = next(iter(data.values())) + elif isinstance(data, (tuple, list)): + assert len(data) > 0 + data = data[0] + elif isinstance(data, (tuple, list)): + assert len(data) > 0 + data = data[0] + + return len(data) diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/mlflow.py b/gafl/build/geometric-algebra-transformer/gatr/utils/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2f5ff71c02d75c9b5244f3e3d66c4738d18607 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/mlflow.py @@ -0,0 +1,68 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import time +from typing import Optional, Union + +import mlflow +import numpy as np + +from gatr.utils.logger import logger + +MAX_LOG_ATTEMPTS = 20 +BASE_WAIT_TIME = 0.2 # Base wait time between attempts in seconds +WAIT_TIME_FACTOR = 1.5 # Increase of the wait time for each successive trial +WAIT_TIME_RANDOM = ( + 0.5 # Upper bound on random wait time that is added to break synchronicity of multiple jobs +) + +LOGGING_ENABLED = True + + +def log_mlflow( + key: str, value: Union[float, str], step: Optional[int] = None, kind: str = "metric" +) -> None: + """Logs metric or param to MLflow. + + Catches exceptions due to locked or unavailable DB and then retries. + + Parameters + ---------- + key : str + Key to log + value : float or str + Value to log + step : None or int + Step to log + kind : {"metric", "param"} + Whether to log a metric or a parameter + + Raises + ------ + ValueError + If `kind` is invalid + """ + if not LOGGING_ENABLED: + return + + for attempt in range(MAX_LOG_ATTEMPTS): + try: + if kind == "metric": + mlflow.log_metric(key, value, step=step) + elif kind == "param": + mlflow.log_param(key, value) + else: + raise ValueError( + f"Unknown MLflow logging kind {kind}, should be 'metric' or 'param'" + ) + return + except Exception: # pylint: disable=broad-except + wait_time = ( + BASE_WAIT_TIME * WAIT_TIME_FACTOR**attempt + WAIT_TIME_RANDOM * np.random.rand() + ) + logger.warning( + f"Exception when logging to MLflow at step {step} (attempt {attempt + 1}). " + f"Waiting for {wait_time:.1f}s before trying again." + ) + time.sleep(wait_time) + + logger.error(f"Warning: Failed to write to MLflow {MAX_LOG_ATTEMPTS} times") diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/plotting.py b/gafl/build/geometric-algebra-transformer/gatr/utils/plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..85755260ccd3d7137c6cfe60fb7bac30f6dd9999 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/plotting.py @@ -0,0 +1,42 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Matplotlib plotting settings.""" + +FONTSIZE = 11 # pt +PAGEWIDTH = 11 # inches +MATPLOTLIB_PARAMS = { + # Font sizes + "font.size": FONTSIZE, # controls default text sizes + "axes.titlesize": FONTSIZE, # fontsize of the axes title + "axes.labelsize": FONTSIZE, # fontsize of the x and y labels + "xtick.labelsize": FONTSIZE, # fontsize of the tick labels + "ytick.labelsize": FONTSIZE, # fontsize of the tick labels + "legend.fontsize": FONTSIZE, # legend fontsize + "figure.titlesize": FONTSIZE, # fontsize of the figure title + # Figure size and DPI + "figure.dpi": 100, + "savefig.dpi": 300, + "figure.figsize": (PAGEWIDTH / 2, PAGEWIDTH / 2), + # colors + "lines.markeredgewidth": 0.8, + "axes.edgecolor": "black", + "axes.grid": False, + "grid.color": "0.9", + "axes.grid.which": "both", + # x-axis ticks and grid + "xtick.bottom": True, + "xtick.direction": "out", + "xtick.color": "black", + "xtick.major.bottom": True, + "xtick.major.size": 4, + "xtick.minor.bottom": True, + "xtick.minor.size": 2, + # y-axis ticks and grid + "ytick.left": True, + "ytick.direction": "out", + "ytick.color": "black", + "ytick.major.left": True, + "ytick.major.size": 4, + "ytick.minor.left": True, + "ytick.minor.size": 2, +} diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/quaternions.py b/gafl/build/geometric-algebra-transformer/gatr/utils/quaternions.py new file mode 100644 index 0000000000000000000000000000000000000000..f720a57afe81d286f9102a2e2fd287e0a0bfa400 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/quaternions.py @@ -0,0 +1,66 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +"""Adapted from the below. + +https://github.com/pimdh/lie-vae/blob/c473d91c494b9e80f6ac2998b1b6b927d09df259/lie_vae/lie_tools.py +by Luca Falorsi, Pim de Haan, Tim Davidson at https://github.com/pimdh/lie-vae + +MIT License + +Copyright (c) 2020 Pim de Haan, Luca Falorsi, Tim Davidson + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +""" + +import torch + + +def random_quaternion(batch_dims): + """Returns a unit quaternion, uniformly sampled from the 3-sphere.""" + q = torch.randn(*batch_dims, 4) + return q / torch.norm(q, dim=-1, keepdim=True) + + +def quaternion_to_rotation_matrix(q): + """Normalises q and maps to group matrix. + + Assumes [x y z w] quaternion format with ij=k (Hamilton) convention. + """ + q = q[..., [3, 0, 1, 2]] # Convert to [w x y z] order + + q = q / q.norm(p=2, dim=-1, keepdim=True) + r, i, j, k = q[..., 0], q[..., 1], q[..., 2], q[..., 3] + + mat = torch.stack( + [ + r * r + i * i - j * j - k * k, + 2 * (i * j - k * r), + 2 * (i * k + j * r), + 2 * (i * j + k * r), + r * r - i * i + j * j - k * k, + 2 * (j * k - i * r), + 2 * (i * k - j * r), + 2 * (j * k + i * r), + r * r - i * i - j * j + k * k, + ], + -1, + ) + + return mat.view(*q.shape[:-1], 3, 3) diff --git a/gafl/build/geometric-algebra-transformer/gatr/utils/tensors.py b/gafl/build/geometric-algebra-transformer/gatr/utils/tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..5bad296c6d07df48465d236df17a86e65e8ba3c7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/gatr/utils/tensors.py @@ -0,0 +1,96 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Union + +import torch +from torch import Tensor + + +def expand_pairwise(*tensors, exclude_dims=()): + """Expand tensors to largest, optionally excluding some axes.""" + max_dim = max(t.dim() for t in tensors) + shapes = [(1,) * (max_dim - t.dim()) + t.shape for t in tensors] + max_shape = [max(s[d] for s in shapes) for d in range(max_dim)] + for d in exclude_dims: + max_shape[d] = -1 + return tuple(t.expand(tuple(max_shape)) for t in tensors) + + +def to_nd(tensor, d): + """Make tensor n-dimensional, group extra dimensions in first.""" + return tensor.view(-1, *(1,) * (max(0, d - 1 - tensor.dim())), *tensor.shape[-(d - 1) :]) + + +def assert_equal(vals): + """Assert all values in sequence are equal.""" + for v in vals: + assert v == vals[0] + + +def block_stack(tensors, dim1, dim2): + """Block diagonally stack tensors along dimensions dim1 and dim2.""" + assert_equal([t.dim() for t in tensors]) + shapes = [t.shape for t in tensors] + shapes_t = list(map(list, zip(*shapes))) + for i, ss in enumerate(shapes_t): + if i not in (dim1, dim2): + assert_equal(ss) + + dim2_len = sum(shapes_t[dim2]) + opts = dict(device=tensors[0].device, dtype=tensors[0].dtype) + + padded_tensors = [] + offset = 0 + for tensor in tensors: + before_shape = list(tensor.shape) + before_shape[dim2] = offset + after_shape = list(tensor.shape) + after_shape[dim2] = dim2_len - tensor.shape[dim2] - offset + before = torch.zeros(*before_shape, **opts) + after = torch.zeros(*after_shape, **opts) + padded = torch.cat([before, tensor, after], dim2) + padded_tensors.append(padded) + offset += tensor.shape[dim2] + return torch.cat(padded_tensors, dim1) + + +def construct_reference_multivector(reference: Union[Tensor, str], inputs: Tensor) -> Tensor: + """Constructs a reference vector for the equivariant join. + + Parameters + ---------- + reference : Tensor with shape (..., 16) or {"data", "canonical"} + Reference multivector for the equivariant joint operation. If "data", a + reference multivector is constructed from the mean of the input multivectors. If + "canonical", a constant canonical reference multivector is used instead. + inputs : Tensor with shape (..., num_items_1, num_items_2, in_mv_channels, 16) + Input multivectors. + + Returns + ------- + reference_mv : Tensor with shape (..., 16) + Reference multivector for the equivariant join. + + Raises + ------ + ValueError + If `reference` is neither "data", "canonical", nor a Tensor. + """ + + if reference == "data": + # When using torch-geometric-style batching, this code should be adapted to perform the + # mean over the items in each batch, but not over the batch dimension. + # We leave this as an exercise for the practitioner :) + mean_dim = tuple(range(1, len(inputs.shape) - 1)) + reference_mv = torch.mean(inputs, dim=mean_dim, keepdim=True) # (batch, 1, ..., 1, 16) + elif reference == "canonical": + reference_mv = torch.zeros(16).to(inputs.device, inputs.dtype) + reference_mv[..., [14, 15]] = 1.0 + else: + if not isinstance(reference, Tensor): + raise ValueError( + 'Reference needs to be "data", "canonical", or torch.Tensor, but found {reference}' + ) + reference_mv = reference + + return reference_mv diff --git a/gafl/build/geometric-algebra-transformer/img/gatr.png b/gafl/build/geometric-algebra-transformer/img/gatr.png new file mode 100644 index 0000000000000000000000000000000000000000..cb06e4e0c0697cf0e3a2ab99321540f70f6fa322 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/img/gatr.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0d7a9d6a2adaf232c1c44a82586e468c72275e77c9acd58484a819363f9cdf5 +size 93832 diff --git a/gafl/build/geometric-algebra-transformer/pyproject.toml b/gafl/build/geometric-algebra-transformer/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..12479df07dc0d6afae3d13e8f51aa6e99ea6026f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/pyproject.toml @@ -0,0 +1,41 @@ +[tool.black] +line-length = 100 +extend-exclude = "notebooks" + +[tool.isort] +sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"] +profile = "black" +line_length = 100 +extend_skip_glob = ["notebooks/*"] + +[tool.mypy] +warn_unused_configs = true +show_error_codes = true +check_untyped_defs = true +no_implicit_optional = true +disallow_untyped_defs = false +strict_equality = true + +[[tool.mypy.overrides]] +module = [ + "cliffordlayers.*", + "clifford.*", + "coronary_mesh_convolution.*", + "dgl.*", + "e3nn.*", + "matplotlib.*", + "mlflow.*", + "mock.*", + "opt_einsum.*", + "pandas", + "rope.*", + "scipy.*", + "seaborn", + "setuptools.*", + "torch.*", + "torch_ema.*", + "torch_geometric.*", + "torch_scatter.*", + "xformers.*", +] +ignore_missing_imports = true diff --git a/gafl/build/geometric-algebra-transformer/scripts/__init__.py b/gafl/build/geometric-algebra-transformer/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/scripts/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/scripts/artery_experiment.py b/gafl/build/geometric-algebra-transformer/scripts/artery_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..11d8b408768c0d7baab66bc659872f019c339454 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/scripts/artery_experiment.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.arteries.experiment import ArteryExperiment + + +@hydra.main(config_path="../config", config_name="arteries", version_base=None) +def main(cfg): + """Entry point for artery experiment.""" + exp = ArteryExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/scripts/generate_nbody_dataset.py b/gafl/build/geometric-algebra-transformer/scripts/generate_nbody_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc71e0b351211a3c2d9d08ee6dfa0c1e5acfceb --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/scripts/generate_nbody_dataset.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +from pathlib import Path + +import hydra +import numpy as np + +from gatr.experiments.nbody import NBodySimulator + + +def generate_dataset(filename, simulator, num_samples, num_planets=5, domain_shift=False): + """Samples from n-body simulator and stores the results at `filename`.""" + assert not Path(filename).exists() + m, x_initial, v_initial, x_final, trajectories = simulator.sample( + num_samples, num_planets=num_planets, domain_shift=domain_shift + ) + np.savez( + filename, + m=m, + x_initial=x_initial, + v_initial=v_initial, + x_final=x_final, + trajectories=trajectories, + ) + + +def generate_datasets(path): + """Generates a canonical set of datasets for the n-body problem, stores them in `path`.""" + path = Path(path).resolve() + path.mkdir(parents=True, exist_ok=True) + + print(f"Creating gravity dataset in {str(path)}") + + simulator = NBodySimulator() + generate_dataset(path / "train.npz", simulator, 100000, num_planets=3, domain_shift=False) + generate_dataset(path / "val.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset(path / "eval.npz", simulator, 5000, num_planets=3, domain_shift=False) + generate_dataset( + path / "e3_generalization.npz", simulator, 5000, num_planets=3, domain_shift=True + ) + generate_dataset( + path / "object_generalization.npz", simulator, 5000, num_planets=5, domain_shift=False + ) + + print("Done, have a nice day!") + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body dataset generation.""" + data_dir = cfg.data.data_dir + np.random.seed(cfg.seed) + generate_datasets(data_dir) + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/scripts/nbody_experiment.py b/gafl/build/geometric-algebra-transformer/scripts/nbody_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..36d4863843d54ec23f14c6da8214b580868d40a9 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/scripts/nbody_experiment.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +import hydra + +from gatr.experiments.nbody import NBodyExperiment + + +@hydra.main(config_path="../config", config_name="nbody", version_base=None) +def main(cfg): + """Entry point for n-body experiment.""" + exp = NBodyExperiment(cfg) + exp() + + +if __name__ == "__main__": + main() diff --git a/gafl/build/geometric-algebra-transformer/setup.py b/gafl/build/geometric-algebra-transformer/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2a7dbf9c428bfc03088ee546a6ffacc2adbc0739 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/setup.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. + +from pathlib import Path +from typing import List + +from setuptools import find_packages, setup + +extra_files: List[str] = [ + "primitives/data/geometric_product.pt", + "primitives/data/outer_product.pt", +] + +_CURRENT_FOLDER = Path(__file__).parent +_PYTHON_FILES_IN_SCRIPTS = list((_CURRENT_FOLDER / "scripts").glob("*.py")) + +scripts = [ + s.relative_to(_CURRENT_FOLDER).as_posix() + for s in _PYTHON_FILES_IN_SCRIPTS + if "__" not in str(s) +] +package_list = find_packages(exclude=["tests*", "docker", "scripts"]) + + +def get_version(rel_path: Path) -> str: + """Extracts version information. + + Inspired by item "1." @ https://packaging.python.org/guides/single-sourcing-package-version/. + """ + package_init_path = Path(__file__).parent / rel_path + with package_init_path.open() as f: + for line in f: + if line.startswith("__version__"): + delimiter = '"' if '"' in line else "'" + return line.split(delimiter)[1] + raise RuntimeError(f"Unable to find version string in {package_init_path}.") + + +setup( + name="GATr", + version=get_version(Path("gatr") / "__init__.py"), + author="Johann Brehmer, Pim de Haan, Sönke Behrends, and Taco Cohen", + author_email="jbrehmer@qti.qualcomm.com", + maintainer="Johann Brehmer", + maintainer_email="jbrehmer@qti.qualcomm.com", + url="https://github.com/Qualcomm-AI-research/geometric-algebra-transformer", + description="The Geometric Algebra Transformer, a universal neural network architecture for geometric data", + license="See notice in license file", + packages=package_list, + scripts=scripts, + package_data={"gatr": extra_files}, + include_package_data=True, + python_requires=">=3.8", + install_requires=[ + "einops", + "numpy<1.25", + "opt_einsum @ git+https://github.com/dgasmith/opt_einsum.git@1a984b7b75f3e532e7129f6aa13f7ddc3da66e10", + "torch>=2.0", + "xformers", + ], +) diff --git a/gafl/build/geometric-algebra-transformer/tests/__init__.py b/gafl/build/geometric-algebra-transformer/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/conftest.py b/gafl/build/geometric-algebra-transformer/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0acd14ca6bc9bd2d0d79452c66462e70fdd84a --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/conftest.py @@ -0,0 +1,10 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +from click.testing import CliRunner + + +@pytest.fixture(scope="function") +def click_runner() -> CliRunner: + """Returns a CLI runner.""" + return CliRunner() diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/__init__.py b/gafl/build/geometric-algebra-transformer/tests/gatr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/baselines/test_transformer.py b/gafl/build/geometric-algebra-transformer/tests/gatr/baselines/test_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd4daf30c98ab14343e16b329e05109260ae001 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/baselines/test_transformer.py @@ -0,0 +1,70 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.baselines.transformer import BaselineAxialTransformer, BaselineTransformer +from tests.helpers import BATCH_DIMS + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_items", [5]) +@pytest.mark.parametrize("in_channels,hidden_channels,out_channels", [(7, 8, 9)]) +@pytest.mark.parametrize("num_heads", [4]) +@pytest.mark.parametrize("num_blocks", [3]) +@pytest.mark.parametrize("pos_encoding", [False, True]) +def test_transformer_shape( + batch_dims, + num_items, + in_channels, + hidden_channels, + out_channels, + num_heads, + num_blocks, + pos_encoding, +): + """Tests the output shape of BaselineTransformer.""" + inputs = torch.randn(*batch_dims, num_items, in_channels) + net = BaselineTransformer( + in_channels, + out_channels, + hidden_channels, + num_blocks=num_blocks, + num_heads=num_heads, + pos_encoding=pos_encoding, + ) + outputs = net(inputs) + + assert outputs.shape == (*batch_dims, num_items, out_channels) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_items1,num_items2", [(5, 11)]) +@pytest.mark.parametrize("in_channels,hidden_channels,out_channels", [(7, 8, 9)]) +@pytest.mark.parametrize("num_heads", [4]) +@pytest.mark.parametrize("num_blocks", [3]) +@pytest.mark.parametrize("pos_encodings", [(False, False), (True, False), (True, True)]) +def test_axial_transformer_shape( + batch_dims, + num_items1, + num_items2, + in_channels, + hidden_channels, + out_channels, + num_heads, + num_blocks, + pos_encodings, +): + """Tests the output shape of BaselineAxialTransformer.""" + inputs = torch.randn(*batch_dims, num_items1, num_items2, in_channels) + net = BaselineAxialTransformer( + in_channels, + out_channels, + hidden_channels, + num_blocks=num_blocks, + num_heads=num_heads, + pos_encodings=pos_encodings, + ) + outputs = net(inputs) + + assert outputs.shape == (*batch_dims, num_items1, num_items2, out_channels) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/__init__.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_object.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_object.py new file mode 100644 index 0000000000000000000000000000000000000000..4b86dd9cacf1fe6a5f60729546da022ea985a23d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_object.py @@ -0,0 +1,45 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +import pytest +import torch +from scipy.stats import ortho_group + +from gatr.interface import ( + embed_3d_object, + embed_3d_object_two_vec, + extract_3d_object, + extract_3d_object_two_vec, +) +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("explicit_point", [True, False]) +def test_3d_object_embedding_consistency(batch_dims, explicit_point): + """Tests whether 3D point embeddings into multivectors are cycle consistent.""" + points = torch.randn(*batch_dims, 1, 3) + quaternions = torch.randn(*batch_dims, 1, 4) + quaternions = quaternions / torch.linalg.norm(quaternions, dim=-1, keepdim=True) + + multivectors = embed_3d_object(points, quaternions, explicit_point=explicit_point) + points_reencoded, quats_reencoded = extract_3d_object(multivectors, sign_reference=quaternions) + + torch.testing.assert_close(points, points_reencoded, **TOLERANCES) + torch.testing.assert_close(quaternions, quats_reencoded, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_3d_object_two_vec_embedding_consistency(batch_dims): + """Tests whether 3D point embeddings in the two-vec parameterizations into multivectors are + cycle consistent.""" + point = torch.randn(*batch_dims, 1, 3) + orientation = torch.from_numpy(ortho_group.rvs(3, size=np.product(batch_dims))).to( + torch.float32 + )[..., :2, :] + orientation = orientation.reshape((*batch_dims, 1, 6)) + multivector = embed_3d_object_two_vec(point, orientation=orientation) + point_reencoded, orientation_reencoded = extract_3d_object_two_vec(multivector) + + torch.testing.assert_close(point, point_reencoded, **TOLERANCES) + torch.testing.assert_close(orientation, orientation_reencoded, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_plane.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_plane.py new file mode 100644 index 0000000000000000000000000000000000000000..1231c37c3d1b880b97948aaad53aebde2beff872 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_plane.py @@ -0,0 +1,18 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import embed_oriented_plane, extract_oriented_plane +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_plane_embedding_consistency(batch_dims): + """Tests whether plane embeddings into multivectors are cycle consistent.""" + pos = torch.randn(*batch_dims, 3) + normal = torch.randn(*batch_dims, 3) + normal = normal / torch.linalg.norm(normal, dim=-1, keepdim=True) + multivectors = embed_oriented_plane(normal, position=pos) + normal_extracted = extract_oriented_plane(multivectors) + torch.testing.assert_close(normal, normal_extracted, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_point.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_point.py new file mode 100644 index 0000000000000000000000000000000000000000..7493f8d5a21b75e8c33cff3113aa04573d91e33e --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_point.py @@ -0,0 +1,45 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +import pytest +import torch + +from gatr.interface import embed_point, extract_point, extract_point_embedding_reg +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_point_embedding_consistency(batch_dims): + """Tests whether 3D point embeddings into multivectors are cycle consistent.""" + points = torch.randn(*batch_dims, 3) + multivectors = embed_point(points) + points_reencoded = extract_point(multivectors) + other_mv_components = extract_point_embedding_reg(multivectors) + torch.testing.assert_close(points, points_reencoded, **TOLERANCES) + torch.testing.assert_close( + other_mv_components, torch.zeros_like(other_mv_components), **TOLERANCES + ) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("rescaling", [2.0, -10.0, None]) +def test_point_scaling_invariance(batch_dims, rescaling): + """Tests whether 3D points extracted from multivector are invariant under rescalings of the + multivector.""" + + # If rescaling is None, sample a number (but avoid zero) + if rescaling is None: + while rescaling is None or np.abs(rescaling) < 0.1: + rescaling = np.random.randn() + + multivectors = torch.randn(*batch_dims, 16) + + # Make sure the homogeneous coordinate is not too small + multivectors[..., 14] = torch.where( + abs(multivectors[..., 14]) < 0.1, 0.1, multivectors[..., 14] + ) + + rescaled_multivectors = rescaling * multivectors + points = extract_point(multivectors) + points_from_rescaled = extract_point(rescaled_multivectors) + torch.testing.assert_close(points, points_from_rescaled, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_reflection.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..3391d601833cfabd5f5ead4a8c45eaa29fe3af19 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_reflection.py @@ -0,0 +1,146 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import ( + embed_oriented_plane, + embed_point, + embed_pseudoscalar, + embed_reflection, + embed_scalar, + extract_oriented_plane, + extract_point, + extract_point_embedding_reg, + extract_pseudoscalar, + extract_reflection, + extract_scalar, +) +from gatr.primitives import geometric_product, grade_involute +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_reflection_embedding_consistency(batch_dims): + """Tests whether reflection embeddings into multivectors are cycle consistent.""" + reflection_normals = torch.randn(*batch_dims, 3) + reflection_normals /= torch.linalg.norm(reflection_normals, dim=-1).unsqueeze(-1) + reflection_pos = torch.randn(*batch_dims, 3) + multivectors = embed_reflection(reflection_normals, reflection_pos) + reflection_normals_reencoded = extract_reflection(multivectors) + torch.testing.assert_close(reflection_normals, reflection_normals_reencoded, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("reflection_normal_to_axis", [0, 1, 2]) +def test_reflection_on_point(batch_dims, reflection_normal_to_axis): + """Tests whether the embedding of a reflection along the plane normal to a given coordinate axis + acts on point embeddings as expected.""" + + # Generate input data + points = torch.randn(*batch_dims, 3) + reflection_normal = torch.zeros(3) + reflection_normal[reflection_normal_to_axis] = 1.0 + + # True reflections + reflected_true = torch.clone(points) + reflected_true[..., reflection_normal_to_axis] = -points[..., reflection_normal_to_axis] + + # Embed points and translations into MV + points_embedding = embed_point(points) + reflection_embedding = embed_reflection(reflection_normal, torch.zeros_like(reflection_normal)) + + # Compute translation in multivector space with sandwich product + reflected_sandwich = geometric_product(reflection_embedding, points_embedding) + reflected_sandwich = geometric_product(reflected_sandwich, reflection_embedding) + reflected_sandwich = grade_involute(reflected_sandwich) + other_components_sandwich = extract_point_embedding_reg(reflected_sandwich) + reflected_sandwich = extract_point(reflected_sandwich) + + # Verify that all translation results are consistent + torch.testing.assert_close(reflected_sandwich, reflected_true, **TOLERANCES) + + # Verify that output MVs have other components at zero + torch.testing.assert_close( + other_components_sandwich, torch.zeros_like(other_components_sandwich), **TOLERANCES + ) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("reflection_normal_to_axis", [0, 1, 2]) +def test_reflection_on_plane(batch_dims, reflection_normal_to_axis): + """Tests whether reflection embeddings act on oriented plane embeddings as expected.""" + + # Plane + plane_normals = torch.randn(*batch_dims, 3) + plane_normals /= torch.linalg.norm(plane_normals, dim=-1).unsqueeze(-1) + plane_pos = torch.zeros_like(plane_normals) + plane = embed_oriented_plane(plane_normals, plane_pos) + + # Reflection + reflection_normal = torch.zeros(3) + reflection_normal[reflection_normal_to_axis] = 1.0 + reflection_pos = torch.zeros_like(reflection_normal) + reflection = embed_reflection(reflection_normal, reflection_pos) + + # Reflected plane from sandwich product + reflected_plane = grade_involute( + geometric_product(geometric_product(reflection, plane), reflection) + ) + reflected_normals = extract_oriented_plane(reflected_plane) + + # True reflected plane + reflected_true = torch.clone(plane_normals) + reflected_true[..., reflection_normal_to_axis] = -plane_normals[..., reflection_normal_to_axis] + + # Verify that normals didn't change + torch.testing.assert_close(reflected_normals, reflected_true, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_reflection_on_scalar(batch_dims): + """Tests whether reflections act on scalars as expected.""" + + # Generate input data + inputs = torch.randn(*batch_dims, 1) + reflection_normals = torch.randn(*batch_dims, 3) + reflection_normals /= torch.linalg.norm(reflection_normals, dim=-1).unsqueeze(-1) + reflection_pos = torch.zeros_like(reflection_normals) + + # Embed planes and translations into MV + inputs_embedding = embed_scalar(inputs) + reflection_embedding = embed_reflection(reflection_normals, reflection_pos) + + # Compute translation in multivector space with sandwich product + reflected_inputs = geometric_product(reflection_embedding, inputs_embedding) + reflected_inputs = geometric_product(reflected_inputs, reflection_embedding) + reflected_inputs = grade_involute(reflected_inputs) + reflected_inputs = extract_scalar(reflected_inputs) + + # Verify that normals didn't change + torch.testing.assert_close(reflected_inputs, inputs, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_reflection_on_pseudoscalar(batch_dims): + """Tests whether reflections act on pseudoscalars as expected.""" + + # Generate input data + inputs = torch.randn(*batch_dims, 1) + reflection_normals = torch.randn(*batch_dims, 3) + reflection_normals /= torch.linalg.norm(reflection_normals, dim=-1).unsqueeze(-1) + reflection_pos = torch.zeros_like(reflection_normals) + + # Embed planes and translations into MV + inputs_embedding = embed_pseudoscalar(inputs) + reflection_embedding = embed_reflection(reflection_normals, reflection_pos) + inv_reflection_embedding = reflection_embedding + + # Compute translation in multivector space with sandwich product + reflected_inputs = geometric_product(reflection_embedding, inputs_embedding) + reflected_inputs = geometric_product(reflected_inputs, inv_reflection_embedding) + reflected_inputs = grade_involute(reflected_inputs) + reflected_inputs = extract_pseudoscalar(reflected_inputs) + + # Verify that normals didn't change + torch.testing.assert_close(reflected_inputs, -inputs, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_rotation.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..f71b562666448699c6a0bc067776a0541b11691d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_rotation.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import ( + embed_oriented_plane, + embed_point, + embed_pseudoscalar, + embed_rotation, + embed_scalar, + extract_oriented_plane, + extract_point, + extract_pseudoscalar, + extract_rotation, + extract_scalar, +) +from gatr.primitives.bilinear import geometric_product +from gatr.primitives.linear import reverse +from gatr.utils.quaternions import quaternion_to_rotation_matrix, random_quaternion +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_rotation_embedding_consistency(batch_dims): + """Tests whether rotation embeddings into multivectors are cycle consistent.""" + + quaternions = torch.randn(*batch_dims, 4) + multivectors = embed_rotation(quaternions) + quaternions_reencoded = extract_rotation(multivectors) + torch.testing.assert_close(quaternions, quaternions_reencoded, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_rotation_on_point(batch_dims): + """Tests whether applying rotations to points via matrix-vector multiplication equals rotation + via geometric product.""" + + # Sample random quaternions and points: + q = random_quaternion(batch_dims) + x = torch.randn(*batch_dims, 3) + + # Method 1: Convert to orthogonal matrix and do matrix-vector multiplication + r = quaternion_to_rotation_matrix(q) + rx = torch.einsum("... i j, ... j -> ... i", r, x) + + # Method 2: Embed as multivectors and use sandwich product + m = embed_rotation(q) + p = embed_point(x) + mpm = geometric_product(geometric_product(m, p), reverse(m)) + rxp = embed_point(rx) + mpmx = extract_point(mpm) + + torch.testing.assert_close(mpm, rxp, **TOLERANCES) + torch.testing.assert_close(mpmx, rx, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_rotation_on_plane(batch_dims): + """Tests whether applying rotations to planes via matrix-vector multiplication equals rotation + via geometric product.""" + + # Sample random quaternions and plane normals: + q = random_quaternion(batch_dims) + normals = torch.randn(*batch_dims, 3) + normals /= torch.linalg.norm(normals, dim=-1).unsqueeze(-1) + + # Method 1: Convert to orthogonal matrix and do matrix-vector multiplication + r = quaternion_to_rotation_matrix(q) + rx = torch.einsum("... i j, ... j -> ... i", r, normals) + + # Method 2: Embed as multivectors and use sandwich product + m = embed_rotation(q) + p = embed_oriented_plane(normals, torch.zeros_like(normals)) + mpm = geometric_product(geometric_product(m, p), reverse(m)) + rxp = embed_oriented_plane(rx, torch.zeros_like(normals)) + mpmx = extract_oriented_plane(mpm) + + torch.testing.assert_close(mpm, rxp, **TOLERANCES) + torch.testing.assert_close(mpmx, rx, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_rotation_on_scalar(batch_dims): + """Tests whether rotations act on scalars as expected.""" + + # Scalar + s = torch.randn(*batch_dims, 1) + x = embed_scalar(s) + + # Rotation + q = random_quaternion(batch_dims) + u = embed_rotation(q) + + # Compute rotation with sandwich product + rx = geometric_product(geometric_product(u, x), reverse(u)) + rs = extract_scalar(rx) + + # Verify that scalar didn't change + torch.testing.assert_close(rs, s, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_rotation_on_pseudoscalar(batch_dims): + """Tests whether rotations act on pseudoscalars as expected.""" + + # Scalar + ps = torch.randn(*batch_dims, 1) + x = embed_pseudoscalar(ps) + + # Rotation + q = random_quaternion(batch_dims) + u = embed_rotation(q) + + # Compute rotation with sandwich product + rx = geometric_product(geometric_product(u, x), reverse(u)) + rps = extract_pseudoscalar(rx) + + # Verify that pseudoscalar didn't change + torch.testing.assert_close(rps, ps, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_scalar.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..678144f221634e5f52a576ab2b0ad2bac08b7336 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_scalar.py @@ -0,0 +1,23 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import embed_scalar +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_embed_scalar(batch_dims): + """Tests that embed_scalar() embeds scalars into multivectors correctly.""" + + scalar = torch.randn(*batch_dims, 1) + mv = embed_scalar(scalar) + + # Check that scalar part of MV contains the data we wanted to embed + mv_scalar = mv[..., [0]] + torch.testing.assert_close(mv_scalar, scalar, **TOLERANCES) + + # Check that other components of MV are empty + mv_other = mv[..., 1:] + torch.testing.assert_close(mv_other, torch.zeros_like(mv_other), **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_translation.py b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..3e59de5c2de23d6c5d7c51c7145cc564af11e2fc --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/interface/test_translation.py @@ -0,0 +1,128 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import ( + embed_oriented_plane, + embed_point, + embed_pseudoscalar, + embed_scalar, + embed_translation, + extract_oriented_plane, + extract_point, + extract_point_embedding_reg, + extract_pseudoscalar, + extract_scalar, + extract_translation, +) +from gatr.primitives import geometric_product, reverse +from tests.helpers import BATCH_DIMS, TOLERANCES + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_translation_embedding_consistency(batch_dims): + """Tests whether translation embeddings into multivectors are cycle consistent.""" + translations = torch.randn(*batch_dims, 3) + multivectors = embed_translation(translations) + translations_reencoded = extract_translation(multivectors) + torch.testing.assert_close(translations, translations_reencoded, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_translation_on_point(batch_dims): + """Tests whether translation embeddings act on point embeddings as expected.""" + + # Generate input data + points = torch.randn(*batch_dims, 3) + translation_vectors = torch.randn(*batch_dims, 3) + + # True translation + translated_points_true = points + translation_vectors + + # Embed points and translations into MV + points_embedding = embed_point(points) + translations_embedding = embed_translation(translation_vectors) + inv_translations_embedding = reverse(translations_embedding) + + # Compute translation in multivector space with sandwich product + translated_points_sandwich = geometric_product(translations_embedding, points_embedding) + translated_points_sandwich = geometric_product( + translated_points_sandwich, inv_translations_embedding + ) + other_components_sandwich = extract_point_embedding_reg(translated_points_sandwich) + translated_points_sandwich = extract_point(translated_points_sandwich) + + # Verify that all translation results are consistent + torch.testing.assert_close(translated_points_sandwich, translated_points_true, **TOLERANCES) + + # Verify that output MVs have other components at zero + torch.testing.assert_close( + other_components_sandwich, torch.zeros_like(other_components_sandwich), **TOLERANCES + ) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_translation_on_plane(batch_dims): + """Tests whether translation embeddings act on oriented plane embeddings as expected.""" + + # Generate input data + normals = torch.randn(*batch_dims, 3) + normals /= torch.linalg.norm(normals, dim=-1).unsqueeze(-1) + translation_vectors = torch.randn(*batch_dims, 3) + pos = torch.zeros_like(normals) + + # Embed planes and translations into MV + plane_embedding = embed_oriented_plane(normals, pos) + translations_embedding = embed_translation(translation_vectors) + inv_translations_embedding = reverse(translations_embedding) + + # Compute translation in multivector space with sandwich product + translated_plane_sandwich = geometric_product(translations_embedding, plane_embedding) + translated_plane_sandwich = geometric_product( + translated_plane_sandwich, inv_translations_embedding + ) + translated_normals = extract_oriented_plane(translated_plane_sandwich) + + # Verify that normals didn't change + torch.testing.assert_close(translated_normals, normals, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_translation_on_scalar(batch_dims): + """Tests whether translations act on scalars as expected.""" + + # Scalar + s = torch.randn(*batch_dims, 1) + x = embed_scalar(s) + + # Translation + t = torch.randn(*batch_dims, 3) + u = embed_translation(t) + + # Compute rotation with sandwich product + rx = geometric_product(geometric_product(u, x), reverse(u)) + rs = extract_scalar(rx) + + # Verify that scalar didn't change + torch.testing.assert_close(rs, s, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_translation_on_pseudoscalar(batch_dims): + """Tests whether translations act on pseudoscalars as expected.""" + + # Scalar + ps = torch.randn(*batch_dims, 1) + x = embed_pseudoscalar(ps) + + # Translation + t = torch.randn(*batch_dims, 3) + u = embed_translation(t) + + # Compute translation with sandwich product + rx = geometric_product(geometric_product(u, x), reverse(u)) + rps = extract_pseudoscalar(rx) + + # Verify that pseudoscalar didn't change + torch.testing.assert_close(rps, ps, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/__init__.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_attention.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b272ebe92628a4e6d39c80ac18389b8c7f2c9a38 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_attention.py @@ -0,0 +1,53 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers import SelfAttention, SelfAttentionConfig +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize( + "num_items,in_channels,out_channels,increase_hidden_channels", [(2, 4, 4, 2)] +) +@pytest.mark.parametrize("in_s_channels,out_s_channels", [(17, 13)]) +@pytest.mark.parametrize("num_heads", [4, 1]) +@pytest.mark.parametrize("multi_query", [True, False]) +@pytest.mark.parametrize("pos_encoding", [False, True]) +def test_attention_equivariance( + batch_dims, + num_items, + in_channels, + out_channels, + num_heads, + in_s_channels, + out_s_channels, + pos_encoding, + multi_query, + increase_hidden_channels, +): + """Tests the SelfAttention layer for Pin equivariance, with scalar inputs.""" + + config = SelfAttentionConfig( + in_mv_channels=in_channels, + out_mv_channels=out_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + num_heads=num_heads, + pos_encoding=pos_encoding, + multi_query=multi_query, + increase_hidden_channels=increase_hidden_channels, + ) + layer = SelfAttention(config) + + data_dims = tuple(list(batch_dims) + [num_items, in_channels]) + scalars = torch.randn(*batch_dims, num_items, in_s_channels) + check_pin_equivariance( + layer, + 1, + batch_dims=data_dims, + fn_kwargs=dict(scalars=scalars), + spin=True, + **TOLERANCES, + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_dropout.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..f383d78be5cbe2e3bbfc75462013c2291580b1eb --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_dropout.py @@ -0,0 +1,83 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.dropout import GradeDropout +from tests.helpers import MILD_TOLERANCES, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", [(10,)]) +@pytest.mark.parametrize("p", [0.0, 0.2]) +@pytest.mark.parametrize("training", [True, False]) +def test_dropout_shape(training, p, batch_dims): + """Tests GradeDropout for shape correctness.""" + + layer = GradeDropout(p=p) + if training: + layer.train() + else: + layer.eval() + + mv = torch.randn(*batch_dims, 16) + s = torch.randn(*batch_dims) + out_mv, out_s = layer(mv, s) + + assert out_mv.shape == mv.shape + assert out_s.shape == s.shape + + +@pytest.mark.parametrize("batch_dims", [(10,)]) +@pytest.mark.parametrize("training", [True, False]) +def test_dropout_trivial_limit(training, batch_dims): + """Tests that GradeDropout does nothing when p = 0.""" + + layer = GradeDropout(p=0.0) + if training: + layer.train() + else: + layer.eval() + + mv = torch.randn(*batch_dims, 16) + s = torch.randn(*batch_dims) + out_mv, out_s = layer(mv, s) + + torch.testing.assert_close(out_mv, mv, **TOLERANCES) + torch.testing.assert_close(out_s, s, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", [(10,)]) +@pytest.mark.parametrize("p", [0.0, 0.2]) +@pytest.mark.parametrize("training", [True, False]) +def test_dropout_expectation(training, p, batch_dims, num_trials=10000): + """Tests GradeDropout for correct expectation.""" + + layer = GradeDropout(p=p) + if training: + layer.train() + else: + layer.eval() + + mv = torch.randn(*batch_dims, 16) + s = torch.randn(*batch_dims) + out_mv, out_s = layer( + mv.unsqueeze(0).expand(num_trials, *mv.shape), s.unsqueeze(0).expand(num_trials, *s.shape) + ) + out_mv = out_mv.mean(dim=0) + out_s = out_s.mean(dim=0) + + torch.testing.assert_close( + out_mv, mv, **MILD_TOLERANCES + ) # Over 10k trials we won't get perfect agreement + torch.testing.assert_close(out_s, s, **MILD_TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", [(10,)]) +@pytest.mark.parametrize("p", [0.0, 0.2]) +def test_dropout_equivariance(p, batch_dims): + """Tests GradeDropout for equivariance.""" + + layer = GradeDropout(p=p) + layer.eval() + s = torch.randn(*batch_dims) + check_pin_equivariance(layer, 1, batch_dims=batch_dims, fn_kwargs=dict(scalars=s), **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_geometric_bilinears.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_geometric_bilinears.py new file mode 100644 index 0000000000000000000000000000000000000000..591dcf29af173981226f1de25cd591dbe991471d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_geometric_bilinears.py @@ -0,0 +1,38 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.mlp.geometric_bilinears import GeometricBilinear +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("in_mv_channels", [8]) +@pytest.mark.parametrize("out_mv_channels", [10]) +@pytest.mark.parametrize("in_s_channels", [3]) +@pytest.mark.parametrize("out_s_channels", [5]) +def test_geometric_bilinears_equivariance( + batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels +): + """Tests GeometricBilinear() for equivariance.""" + + layer = GeometricBilinear( + in_mv_channels, + out_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + ) + data_dims = tuple(list(batch_dims) + [in_mv_channels]) + scalars = torch.randn(*batch_dims, in_s_channels) + reference_mv = torch.randn(16) + + # Because of the fixed reference MV, we only test Spin equivariance + check_pin_equivariance( + layer, + 1, + fn_kwargs=dict(scalars=scalars, reference_mv=reference_mv), + batch_dims=data_dims, + spin=True, + **TOLERANCES, + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_linear.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..ce196f9cbcaa18bd1b2e4622755bd4f1a940b33c --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_linear.py @@ -0,0 +1,159 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.linear import EquiLinear +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", [(100,)]) +@pytest.mark.parametrize("in_mv_channels, out_mv_channels", [(200, 5), (16, 16), (5, 200)]) +@pytest.mark.parametrize( + "in_s_channels, out_s_channels", [(None, None), (None, 100), (100, None), (32, 32)] +) +@pytest.mark.parametrize("initialization", ["default", "small", "unit_scalar"]) +def test_linear_layer_initialization( + initialization, + batch_dims, + in_mv_channels, + out_mv_channels, + in_s_channels, + out_s_channels, + var_tolerance=10.0, +): + """Tests the initialization of `EquiLinear`. + + The goal is that independent of the channel size, inputs with variance 1 are mapped to outputs + with, very roughly, variance 1. + """ + + # Create layer + try: + layer = EquiLinear( + in_mv_channels, + out_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + initialization=initialization, + ) + # Some initialization schemes ar enot implemented when data is all-scalar. That's fine. + except NotImplementedError as exc: + print(exc) + return + + # Inputs + inputs_mv = torch.randn(*batch_dims, in_mv_channels, 16) + inputs_s = torch.randn(*batch_dims, in_s_channels) if in_s_channels is not None else None + + # Compute outputs + outputs_mv, outputs_s = layer(inputs_mv, scalars=inputs_s) + + # Compute mean and variance of MV outputs + mv_mean = outputs_mv[...].cpu().detach().to(torch.float64).mean(dim=(0, 1)) + mv_var = outputs_mv[...].cpu().detach().to(torch.float64).var(dim=(0, 1)) + + print("Output multivector means and std by components:") + for i, (mean_, var_) in enumerate(zip(mv_mean, mv_var)): + print(f" Component {i}: mean = {mean_:.2f}, std = {var_**0.5:.2f}") + + # Check that the mean and variance agree with expectations + if initialization == "default": + target_mean = torch.zeros_like(mv_mean) + target_var = torch.ones_like(mv_var) / 3.0 # Factor 3 comes from heuristics + elif initialization == "small": + target_mean = torch.zeros_like(mv_mean) + target_var = 0.01 * torch.ones_like(mv_var) / 3.0 + elif initialization == "unit_scalar": + target_mean = torch.zeros_like(mv_mean) + target_mean[0] = 1.0 + target_var = 0.01 * torch.ones_like(mv_var) / 3.0 + else: + raise ValueError(initialization) + + assert torch.all(mv_mean > target_mean - 0.3) + assert torch.all(mv_mean < target_mean + 0.3) + assert torch.all(mv_var > target_var / var_tolerance) + assert torch.all(mv_var < target_var * var_tolerance) + + # Same for scalar outputs + if out_s_channels is not None: + s_mean = outputs_s[...].cpu().detach().to(torch.float64).mean().item() + s_var = outputs_s[...].cpu().detach().to(torch.float64).var().item() + + print(f"Output scalar: mean = {s_mean:.2f}, std = {s_var**0.5:.2f}") + assert -0.3 < s_mean < 0.3 + if initialization in {"default", "unit_scalar"}: + assert 1.0 / 3.0 / var_tolerance < s_var < 1.0 / 3.0 * var_tolerance + else: + assert 0.01 / 3.0 / var_tolerance < s_var < 0.01 / 3.0 * var_tolerance + + +@pytest.mark.parametrize("rescaling", [0.0, -2.0, 100.0]) +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("in_mv_channels", [9, 1]) +@pytest.mark.parametrize("out_mv_channels", [7, 1]) +@pytest.mark.parametrize("in_s_channels", [None, 3]) +@pytest.mark.parametrize("out_s_channels", [None, 4]) +def test_linear_layer_linearity( + batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, rescaling +): + """Tests that the EquiLinear layer indeed describes a linear map (when the bias is deactivated). + + Checks that `f(x + rescaling * y) = f(x) + rescaling * f(y)` for random inputs `x`, `y` and + linear layer `f(x)`. + """ + layer = EquiLinear( + in_mv_channels, + out_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + bias=False, + ) + + # Inputs + x_mv = torch.randn(*batch_dims, in_mv_channels, 16) + y_mv = torch.randn(*batch_dims, in_mv_channels, 16) + xy_mv = x_mv + rescaling * y_mv + + if in_s_channels: + x_s = torch.randn(*batch_dims, in_s_channels) + y_s = torch.randn(*batch_dims, in_s_channels) + xy_s = x_s + rescaling * y_s + else: + x_s, y_s, xy_s = None, None, None + + # Compute outputs + o_xy_mv, o_xy_s = layer(xy_mv, scalars=xy_s) + o_x_mv, o_x_s = layer(x_mv, scalars=x_s) + o_y_mv, o_y_s = layer(y_mv, scalars=y_s) + + # Check equality + torch.testing.assert_close(o_xy_mv, o_x_mv + rescaling * o_y_mv, **TOLERANCES) + + if out_s_channels is not None: + torch.testing.assert_close(o_xy_s, o_x_s + rescaling * o_y_s, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("in_mv_channels", [9, 1]) +@pytest.mark.parametrize("out_mv_channels", [7, 1]) +@pytest.mark.parametrize("bias", [False, True]) +@pytest.mark.parametrize("in_s_channels", [None, 3]) +@pytest.mark.parametrize("out_s_channels", [None, 4]) +def test_linear_layer_equivariance( + batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias +): + """Tests the equi_linear() primitive for equivariance.""" + layer = EquiLinear( + in_mv_channels, + out_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + bias=bias, + ) + data_dims = tuple(list(batch_dims) + [in_mv_channels]) + scalars = None if in_s_channels is None else torch.randn(*batch_dims, in_s_channels) + check_pin_equivariance( + layer, 1, fn_kwargs=dict(scalars=scalars), batch_dims=data_dims, **TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_mlp.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..9e4c1b34147b0256617b03d5bf8a6754717e2f21 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_mlp.py @@ -0,0 +1,47 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers import GeoMLP +from gatr.layers.mlp.config import MLPConfig +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + +_CHANNELS = [((5,), (12,)), ((4, 8, 7), (10, 9, 3))] + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("activation", ["gelu"]) +@pytest.mark.parametrize("mv_channels,s_channels", _CHANNELS) +def test_geo_mlp_shape(batch_dims, mv_channels, s_channels, activation): + """Tests the output shape of GeoMLP().""" + + inputs = torch.randn(*batch_dims, mv_channels[0], 16) + scalars = None if s_channels is None else torch.randn(*batch_dims, s_channels[0]) + reference_mv = torch.randn(16) + + net = GeoMLP(MLPConfig(mv_channels=mv_channels, s_channels=s_channels, activation=activation)) + outputs, outputs_scalars = net(inputs, reference_mv=reference_mv, scalars=scalars) + assert outputs.shape == (*batch_dims, mv_channels[-1], 16) + assert outputs_scalars.shape == (*batch_dims, s_channels[-1]) + + +@pytest.mark.parametrize("batch_dims", [[100]]) +@pytest.mark.parametrize("activation", ["gelu"]) +@pytest.mark.parametrize("mv_channels,s_channels", _CHANNELS) +def test_geo_mlp_equivariance(batch_dims, mv_channels, s_channels, activation): + """Tests GeoMLP() for Pin equivariance.""" + net = GeoMLP(MLPConfig(mv_channels=mv_channels, s_channels=s_channels, activation=activation)) + data_dims = tuple(list(batch_dims) + [mv_channels[0]]) + scalars = torch.randn(*batch_dims, s_channels[0]) + reference_mv = torch.randn(16) + + # Because of the fixed reference MV, we only test Spin equivariance + check_pin_equivariance( + net, + 1, + batch_dims=data_dims, + fn_kwargs=dict(scalars=scalars, reference_mv=reference_mv), + spin=True, + **TOLERANCES, + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_nonlinearities.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..a998de1fc8b13101f730abba4fb99452dcc612fa --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_nonlinearities.py @@ -0,0 +1,19 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.mlp.nonlinearities import ScalarGatedNonlinearity +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_scalars", [9]) +@pytest.mark.parametrize("activation", ["gelu", "relu", "sigmoid"]) +def test_scalar_gated_nonlinearity_layer_equivariance(activation, batch_dims, num_scalars): + """Tests ScalarGatedNonlinearity() for equivariance.""" + layer = ScalarGatedNonlinearity(nonlinearity=activation) + scalars = torch.randn(*batch_dims, num_scalars) + check_pin_equivariance( + layer, 1, batch_dims=batch_dims, fn_kwargs=dict(scalars=scalars), **TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_normalization.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..865aedc34b58041c09d2ac4c78cc71ebebf26f5d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_normalization.py @@ -0,0 +1,32 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.layer_norm import EquiLayerNorm +from gatr.primitives import norm +from tests.helpers import TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", [(7, 9)]) +@pytest.mark.parametrize("num_scalars", [9]) +def test_equi_layer_norm_layer_correctness(batch_dims, num_scalars): + """Tests whether the output of EquiLayerNorm has the correct variance.""" + inputs = torch.randn(*batch_dims, 16) + scalars = torch.randn(*batch_dims, num_scalars) + layer = EquiLayerNorm(epsilon=1e-9) + normalized_inputs, _ = layer(inputs, scalars=scalars) + dims = tuple(range(1, len(batch_dims) + 1)) + variance = torch.mean(norm(normalized_inputs) ** 2, dim=dims) + torch.testing.assert_close(variance, torch.ones_like(variance), **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", [(7, 9)]) +@pytest.mark.parametrize("num_scalars", [9]) +def test_equi_layer_norm_layer_equivariance(batch_dims, num_scalars): + """Tests EquiLayerNorm() for equivariance.""" + layer = EquiLayerNorm() + scalars = torch.randn(*batch_dims, num_scalars) + check_pin_equivariance( + layer, 1, batch_dims=batch_dims, fn_kwargs=dict(scalars=scalars), **TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_positional_encoding.py b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_positional_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..ca34d7cf831cb7db9433fb7ca5a1703f852f6247 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/layers/test_positional_encoding.py @@ -0,0 +1,28 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers import ApplyRotaryPositionalEncoding +from tests.helpers import BATCH_DIMS + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("additional_dims", [tuple(), (3,), (11, 13)]) +@pytest.mark.parametrize("num_channels", [10]) +@pytest.mark.parametrize("num_objects", [5]) +def test_apply_rotary_positional_encoding(batch_dims, num_objects, additional_dims, num_channels): + """Tests ApplyRotaryPositionalEncoding for consistency.""" + + # Generate input data + data = torch.randn(*batch_dims, num_objects, *additional_dims, num_channels) + item_dim = len(batch_dims) + + # Layer + layer = ApplyRotaryPositionalEncoding(num_channels, item_dim) + + # Outputs + outputs = layer(data) + + # Outputs should have same shape as inputs, except that the number of features is increased + assert outputs.shape == (*batch_dims, num_objects, *additional_dims, num_channels) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_axial_gatr.py b/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_axial_gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..5604a0f639b6da01907e12e3814c3af6c00528b6 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_axial_gatr.py @@ -0,0 +1,114 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.mlp.config import MLPConfig +from gatr.nets import AxialGATr +from tests.helpers import BATCH_DIMS, MILD_TOLERANCES, check_pin_equivariance + +S_CHANNELS = [(None, None, 7, [False, False]), (4, 5, 6, [True, True])] + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize( + "num_items1,num_items2,in_mv_channels,out_mv_channels,hidden_mv_channels", [(8, 11, 6, 4, 8)] +) +@pytest.mark.parametrize("num_heads", [4]) +@pytest.mark.parametrize("num_blocks", [1]) +@pytest.mark.parametrize("in_s_channels,out_s_channels,hidden_s_channels,pos_encoding", S_CHANNELS) +@pytest.mark.parametrize("join_reference", ["data", "canonical"]) +def test_axial_gatr_shape( + batch_dims, + num_items1, + num_items2, + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + num_blocks, + num_heads, + in_s_channels, + out_s_channels, + hidden_s_channels, + pos_encoding, + join_reference, +): + """Tests the output shape of AxialGATr.""" + inputs = torch.randn(*batch_dims, num_items1, num_items2, in_mv_channels, 16) + scalars = ( + None + if in_s_channels is None + else torch.randn(*batch_dims, num_items1, num_items2, in_s_channels) + ) + net = AxialGATr( + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + attention=SelfAttentionConfig(num_heads=num_heads), + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + hidden_s_channels=hidden_s_channels, + num_blocks=num_blocks, + mlp=MLPConfig(), + pos_encodings=pos_encoding, + ) + + outputs, output_scalars = net(inputs, scalars=scalars, join_reference=join_reference) + + assert outputs.shape == (*batch_dims, num_items1, num_items2, out_mv_channels, 16) + if in_s_channels is not None: + assert output_scalars.shape == (*batch_dims, num_items1, num_items2, out_s_channels) + + +@pytest.mark.parametrize("batch_dims", [(64,)]) +@pytest.mark.parametrize( + "num_items1,num_items2,in_mv_channels,out_mv_channels,hidden_mv_channels", [(3, 4, 5, 6, 10)] +) +@pytest.mark.parametrize("num_heads", [4]) +@pytest.mark.parametrize("num_blocks", [1]) +@pytest.mark.parametrize("in_s_channels,out_s_channels,hidden_s_channels,pos_encoding", S_CHANNELS) +def test_axial_gatr_equivariance( + batch_dims, + num_items1, + num_items2, + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + num_blocks, + num_heads, + in_s_channels, + out_s_channels, + hidden_s_channels, + pos_encoding, +): + """Tests AxialGATr for equivariance.""" + try: + net = AxialGATr( + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + attention=SelfAttentionConfig(num_heads=num_heads), + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + hidden_s_channels=hidden_s_channels, + num_blocks=num_blocks, + mlp=MLPConfig(), + pos_encodings=pos_encoding, + ) + except NotImplementedError: + # Some features require scalar inputs, and failing without them is fine + return + + scalars = ( + None + if in_s_channels is None + else torch.randn(*batch_dims, num_items1, num_items2, in_s_channels) + ) + data_dims = tuple(list(batch_dims) + [num_items1, num_items2, in_mv_channels]) + + # We only test for Spin, not Pin, equivariance b/c AxialTransformer currently has some manual breaking of the + # mirror symmetry + check_pin_equivariance( + net, 1, batch_dims=data_dims, fn_kwargs=dict(scalars=scalars), **MILD_TOLERANCES, spin=True + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_gatr.py b/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_gatr.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7ce7b4dba88adc97f7aae100f4d8d4754ef169 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/nets/test_gatr.py @@ -0,0 +1,113 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.mlp.config import MLPConfig +from gatr.nets import GATr +from tests.helpers import BATCH_DIMS, MILD_TOLERANCES, check_pin_equivariance + +S_CHANNELS = [(None, None, 7, False), (4, 5, 6, True)] + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize( + "num_items,in_mv_channels,out_mv_channels,hidden_mv_channels", [(8, 3, 4, 6)] +) +@pytest.mark.parametrize("num_heads,num_blocks", [(4, 1)]) +@pytest.mark.parametrize("in_s_channels,out_s_channels,hidden_s_channels,pos_encoding", S_CHANNELS) +@pytest.mark.parametrize("dropout_prob", [None, 0.0, 0.3]) +@pytest.mark.parametrize("multi_query_attention", [False, True]) +@pytest.mark.parametrize("join_reference", ["data", "canonical"]) +def test_gatr_shape( + batch_dims, + num_items, + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + num_blocks, + num_heads, + in_s_channels, + out_s_channels, + hidden_s_channels, + pos_encoding, + multi_query_attention, + dropout_prob, + join_reference, +): + """Tests the output shape of EquiTransformer.""" + inputs = torch.randn(*batch_dims, num_items, in_mv_channels, 16) + scalars = None if in_s_channels is None else torch.randn(*batch_dims, num_items, in_s_channels) + + try: + net = GATr( + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + hidden_s_channels=hidden_s_channels, + attention=SelfAttentionConfig( + num_heads=num_heads, pos_encoding=pos_encoding, multi_query=multi_query_attention + ), + num_blocks=num_blocks, + mlp=MLPConfig(), + dropout_prob=dropout_prob, + ) + except NotImplementedError: + # Some features require scalar inputs, and failing without them is fine + return + + outputs, output_scalars = net(inputs, scalars=scalars, join_reference=join_reference) + + assert outputs.shape == (*batch_dims, num_items, out_mv_channels, 16) + if in_s_channels is not None: + assert output_scalars.shape == (*batch_dims, num_items, out_s_channels) + + +@pytest.mark.parametrize("batch_dims", [(64,)]) +@pytest.mark.parametrize( + "num_items,in_mv_channels,out_mv_channels,hidden_mv_channels", [(8, 3, 4, 6)] +) +@pytest.mark.parametrize("num_heads,num_blocks", [(4, 1)]) +@pytest.mark.parametrize("in_s_channels,out_s_channels,hidden_s_channels,pos_encoding", S_CHANNELS) +@pytest.mark.parametrize("multi_query_attention", [False, True]) +def test_gatr_equivariance( + batch_dims, + num_items, + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + num_blocks, + num_heads, + in_s_channels, + out_s_channels, + hidden_s_channels, + pos_encoding, + multi_query_attention, +): + """Tests GATr for equivariance.""" + try: + net = GATr( + in_mv_channels, + out_mv_channels, + hidden_mv_channels, + in_s_channels=in_s_channels, + out_s_channels=out_s_channels, + hidden_s_channels=hidden_s_channels, + attention=SelfAttentionConfig( + num_heads=num_heads, pos_encoding=pos_encoding, multi_query=multi_query_attention + ), + num_blocks=num_blocks, + mlp=MLPConfig(), + ) + except NotImplementedError: + # Some features require scalar inputs, and failing without them is fine + return + + scalars = None if in_s_channels is None else torch.randn(*batch_dims, num_items, in_s_channels) + data_dims = tuple(list(batch_dims) + [num_items, in_mv_channels]) + check_pin_equivariance( + net, 1, batch_dims=data_dims, fn_kwargs=dict(scalars=scalars), **MILD_TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/__init__.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_attention.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..5abf361322474780e440fd57ec500321326413e0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_attention.py @@ -0,0 +1,215 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.interface import embed_point, embed_scalar +from gatr.primitives import geometric_attention, pga_attention, sdp_attention +from gatr.primitives.attention import lin_square_normalizer +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_s_channels_out", [11, 1]) +@pytest.mark.parametrize("num_s_channels_in", [17, 1]) +@pytest.mark.parametrize("num_mv_channels_out", [3, 1]) +@pytest.mark.parametrize("num_mv_channels_in", [2, 1]) +@pytest.mark.parametrize("num_tokens_out", [5, 1]) +@pytest.mark.parametrize("num_tokens_in", [7, 1]) +def test_scalar_attention_shape( + batch_dims, + num_tokens_in, + num_tokens_out, + num_mv_channels_in, + num_mv_channels_out, + num_s_channels_in, + num_s_channels_out, +): + """Tests that outputs of scalar_attention() have correct shape.""" + # Generate inputs + q_mv = torch.randn(*batch_dims, num_tokens_out, num_mv_channels_in, 16) + k_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_in, 16) + v_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_out, 16) + q_s = torch.randn(*batch_dims, num_tokens_out, num_s_channels_in) + k_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_in) + v_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_out) + + # Compute attention outputs + outputs, outputs_scalar = sdp_attention(q_mv, k_mv, v_mv, q_s, k_s, v_s) + + # Check shape of outputs + assert outputs.shape == (*batch_dims, num_tokens_out, num_mv_channels_out, 16) + assert outputs_scalar.shape == (*batch_dims, num_tokens_out, num_s_channels_out) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_s_channels_out", [11, 1]) +@pytest.mark.parametrize("num_s_channels_in", [17, 1]) +@pytest.mark.parametrize("num_mv_channels_out", [3, 1]) +@pytest.mark.parametrize("num_mv_channels_in", [2, 1]) +@pytest.mark.parametrize("num_tokens_out", [5, 1]) +@pytest.mark.parametrize("num_tokens_in", [7, 1]) +def test_pga_attention_shape( + batch_dims, + num_tokens_in, + num_tokens_out, + num_mv_channels_in, + num_mv_channels_out, + num_s_channels_in, + num_s_channels_out, +): + """Tests that outputs of pga_attention() have correct shape.""" + # Generate inputs + q_mv = torch.randn(*batch_dims, num_tokens_out, num_mv_channels_in, 16) + k_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_in, 16) + v_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_out, 16) + q_s = torch.randn(*batch_dims, num_tokens_out, num_s_channels_in) + k_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_in) + v_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_out) + weights = ( # Weights need to be non-negative + torch.exp(torch.randn(num_mv_channels_in)), + torch.exp(torch.randn(num_mv_channels_in)), + torch.exp(torch.randn(num_s_channels_in)), + ) + + # Compute attention outputs + outputs, outputs_scalar = pga_attention(q_mv, k_mv, v_mv, q_s, k_s, v_s, weights=weights) + + # Check shape of outputs + assert outputs.shape == (*batch_dims, num_tokens_out, num_mv_channels_out, 16) + assert outputs_scalar.shape == (*batch_dims, num_tokens_out, num_s_channels_out) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_s_channels_out", [11, 1]) +@pytest.mark.parametrize("num_s_channels_in", [17, 1]) +@pytest.mark.parametrize("num_mv_channels_out", [3, 1]) +@pytest.mark.parametrize("num_mv_channels_in", [2, 1]) +@pytest.mark.parametrize("num_tokens_out", [5, 1]) +@pytest.mark.parametrize("num_tokens_in", [7, 1]) +def test_geometric_attention_shape( + batch_dims, + num_tokens_in, + num_tokens_out, + num_mv_channels_in, + num_mv_channels_out, + num_s_channels_in, + num_s_channels_out, +): + """Tests that outputs of geometric_attention() have correct shape.""" + # Generate inputs + q_mv = torch.randn(*batch_dims, num_tokens_out, num_mv_channels_in, 16) + k_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_in, 16) + v_mv = torch.randn(*batch_dims, num_tokens_in, num_mv_channels_out, 16) + q_s = torch.randn(*batch_dims, num_tokens_out, num_s_channels_in) + k_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_in) + v_s = torch.randn(*batch_dims, num_tokens_in, num_s_channels_out) + + # Compute attention outputs + outputs, outputs_scalar = geometric_attention( + q_mv, k_mv, v_mv, q_s, k_s, v_s, normalizer=lin_square_normalizer + ) + + # Check shape of outputs + assert outputs.shape == (*batch_dims, num_tokens_out, num_mv_channels_out, 16) + assert outputs_scalar.shape == (*batch_dims, num_tokens_out, num_s_channels_out) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_scalars", [5]) +@pytest.mark.parametrize("key_dim", [2]) +@pytest.mark.parametrize("item_dim", [3]) +def test_scalar_attention_equivariance(batch_dims, key_dim, item_dim, num_scalars): + """Tests scalar_attention() for Pin equivariance.""" + data_dims = tuple(list(batch_dims) + [item_dim, key_dim]) + queries_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + keys_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + values_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + kwargs = dict(q_s=queries_scalar, k_s=keys_scalar, v_s=values_scalar) + check_pin_equivariance(sdp_attention, 3, batch_dims=data_dims, fn_kwargs=kwargs, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_scalars", [5]) +@pytest.mark.parametrize("key_dim", [2]) +@pytest.mark.parametrize("item_dim", [3]) +def test_pga_attention_equivariance(batch_dims, key_dim, item_dim, num_scalars): + """Tests pga_attention() for Pin equivariance.""" + data_dims = tuple(list(batch_dims) + [item_dim, key_dim]) + queries_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + keys_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + values_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + weights = ( # Weights need to be non-negative + torch.exp(torch.randn(key_dim)), + torch.exp(torch.randn(key_dim)), + torch.exp(torch.randn(num_scalars)), + ) + kwargs = dict(q_s=queries_scalar, k_s=keys_scalar, v_s=values_scalar, weights=weights) + check_pin_equivariance(pga_attention, 3, batch_dims=data_dims, fn_kwargs=kwargs, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("num_scalars", [5]) +@pytest.mark.parametrize("key_dim", [2]) +@pytest.mark.parametrize("item_dim", [3]) +def test_geometric_attention_equivariance(batch_dims, key_dim, item_dim, num_scalars): + """Tests geometric_attention() for Pin equivariance.""" + data_dims = tuple(list(batch_dims) + [item_dim, key_dim]) + queries_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + keys_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + values_scalar = torch.randn(*batch_dims, item_dim, num_scalars) + kwargs = dict(q_s=queries_scalar, k_s=keys_scalar, v_s=values_scalar, normalizer=lambda v: 1.0) + check_pin_equivariance( + geometric_attention, 3, batch_dims=data_dims, fn_kwargs=kwargs, **TOLERANCES + ) + + +def test_pga_attention_proximity(): + """Tests that with the right weights, pga_attention attends to nearby points.""" + + # Data + q_mv = embed_point(torch.zeros(1, 1, 3)) # (1, 1, 16), point at the origin + k_mv = embed_point( + torch.tensor([[[1.0, 0.0, 0.0]], [[0.0, 100.0, 0.0]]]) + ) # (2, 1, 16), close point and far point + v_mv = embed_scalar( + torch.tensor([[[1.0], [0.0]], [[0.0], [1.0]]]) + ) # (2, 2, 16), one-hot encoding of what was attended to + q_s = torch.zeros(1, 1) # we don't care about scalars + k_s = torch.zeros(2, 1) + v_s = torch.zeros(2, 1) + weights = torch.tensor( + [0.0, 1.0, 0.0] + ) # Only attend based on join - not inner products or aux scalars + + # Compute attention + out_mv, out_s = pga_attention(q_mv, k_mv, v_mv, q_s, k_s, v_s, weights) + + # Check that we attended to closer one + torch.testing.assert_close(out_mv, v_mv[[0]], **TOLERANCES) + torch.testing.assert_close(out_s, v_s[[0]], **TOLERANCES) + + +def test_geometric_attention_proximity(): + """Tests that with the right weights, geometric_attention attends to nearby points.""" + + # Data + q_mv = embed_point(torch.zeros(1, 1, 3)) # (1, 1, 16), point at the origin + k_mv = embed_point( + torch.tensor([[[1.0, 0.0, 0.0]], [[0.0, 100.0, 0.0]]]) + ) # (2, 1, 16), close point and far point + v_mv = embed_scalar( + torch.tensor([[[1.0], [0.0]], [[0.0], [1.0]]]) + ) # (2, 2, 16), one-hot enc of attn target + q_s = torch.zeros(1, 1) # we don't care about scalars + k_s = torch.zeros(2, 1) + v_s = torch.zeros(2, 1) + + # Compute attention + out_mv, out_s = geometric_attention( + q_mv, k_mv, v_mv, q_s, k_s, v_s, normalizer=lin_square_normalizer + ) + + # Check that we attended to closer one + torch.testing.assert_close(out_mv, v_mv[[0]], **TOLERANCES) + torch.testing.assert_close(out_s, v_s[[0]], **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_bilinear.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_bilinear.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2ad683b5e182cd076b2b3374fc1fefa0ad6e59 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_bilinear.py @@ -0,0 +1,42 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of bilinear primitives.""" + +import pytest + +from gatr.primitives.bilinear import geometric_product, outer_product +from tests.helpers import ( + BATCH_DIMS, + TOLERANCES, + check_consistence_with_geometric_product, + check_consistence_with_outer_product, + check_pin_equivariance, +) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_geometric_product_correctness(batch_dims): + """Tests the geometric_product() primitive for correctness (that is, consistency with the + clifford library). + """ + check_consistence_with_geometric_product(geometric_product, batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_outer_product_correctness(batch_dims): + """Tests the outer_product() primitive for correctness (that is, consistency with the clifford + library). + """ + check_consistence_with_outer_product(outer_product, batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_geometric_product_equivariance(batch_dims): + """Tests the geometric_product() primitive for equivariance.""" + check_pin_equivariance(geometric_product, 2, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_outer_product_equivariance(batch_dims): + """Tests the outer_product() primitive for equivariance.""" + check_pin_equivariance(outer_product, 2, batch_dims=batch_dims, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dropout.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..b66d5d6055dce634b4b568d1abfa3a14ceb59a2c --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dropout.py @@ -0,0 +1,53 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import pytest +import torch + +from gatr.primitives.dropout import grade_dropout +from tests.helpers import BATCH_DIMS, MILD_TOLERANCES, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("p", [0.0, 0.2]) +@pytest.mark.parametrize("training", [True, False]) +def test_dropout_shape(training, p, batch_dims): + """Tests grade_dropout() map for shape correctness.""" + x = torch.randn(*batch_dims, 16) + y = grade_dropout(x, p=p, training=training) + assert y.shape == x.shape + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("training", [False, True]) +def test_dropout_trivial_limit(training, batch_dims): + """Tests that grade_dropout() does nothing when p = 0.""" + x = torch.randn(*batch_dims, 16) + y = grade_dropout(x, p=0.0, training=training) + + torch.testing.assert_close(x, y, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("p", [0.0, 0.2]) +def test_dropout_expectation(p, batch_dims, num_trials=10000): + """Tests that grade_dropout() has train-time and test-time behaviour that is identical in + expectation.""" + x = torch.randn(*batch_dims, 16) + y_train = grade_dropout(x.unsqueeze(0).expand(num_trials, *x.shape), p=p, training=True).mean( + dim=0 + ) + y_test = grade_dropout(x, p=p, training=False) + + torch.testing.assert_close(y_test, x, **TOLERANCES) + torch.testing.assert_close( + y_train, x, **MILD_TOLERANCES + ) # Over 10k trials we won't get perfect agreement + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +@pytest.mark.parametrize("p", [0.0, 0.2]) +def test_dropout_equivariance(p, batch_dims): + """Tests the grade_dropout() primitive for equivariance (at test time).""" + check_pin_equivariance( + grade_dropout, 1, batch_dims=batch_dims, fn_kwargs=dict(training=False, p=p), **TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dual.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dual.py new file mode 100644 index 0000000000000000000000000000000000000000..97f22231e95c3a9be2a70b3cf4d1b23f836e01a1 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_dual.py @@ -0,0 +1,57 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of bilinear primitives.""" + +import pytest +import torch + +from gatr.primitives.dual import ( + dual, + efficient_equivariant_join, + equivariant_join, + explicit_equivariant_join, + join_norm, +) +from gatr.primitives.invariants import norm +from tests.helpers import ( + BATCH_DIMS, + TOLERANCES, + check_consistence_with_dual, + check_pin_equivariance, +) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_dual_correctness(batch_dims): + """Tests that dual() computes the correct dual.""" + check_consistence_with_dual(dual, batch_dims) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_join_norm_correctness(batch_dims): + """Tests the join_norm() primitive for correctness.""" + x = torch.randn(*batch_dims, 16) + y = torch.randn(*batch_dims, 16) + reference = torch.randn(*batch_dims, 16) + + true_result = norm(equivariant_join(x, y, reference) / torch.abs(reference[..., [14]])) + result = join_norm(x, y) + torch.testing.assert_close(result, true_result) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_join_equivariance(batch_dims): + """Tests the join() primitive for equivariance.""" + check_pin_equivariance(equivariant_join, 3, batch_dims=batch_dims, **TOLERANCES, num_checks=10) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_efficient_join_implementation_equivalence(batch_dims): + """Tests that efficient_reference_dual() and explicit_reference_dual() agree.""" + x = torch.randn(*batch_dims, 16) + y = torch.randn(*batch_dims, 16) + reference = torch.randn(*batch_dims, 16) + + result_expl = explicit_equivariant_join(x, y, reference) + result_eff = efficient_equivariant_join(x, y, reference) + torch.testing.assert_close(result_expl, result_eff) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_invariants.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_invariants.py new file mode 100644 index 0000000000000000000000000000000000000000..4b74eac0b363b00193c4acf64ce2cc0996700a52 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_invariants.py @@ -0,0 +1,67 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of bilinear primitives.""" + +import pytest +import torch + +from gatr.primitives import inner_product, norm, pin_invariants +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_invariance + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_norm_correctness(batch_dims): + """Checks that norm() is consistent with inner_product().""" + inputs = torch.randn(*batch_dims, 16) + norms = norm(inputs) + true_norms = torch.sqrt(inner_product(inputs, inputs)) + torch.testing.assert_close(norms, true_norms) + + +@pytest.mark.parametrize( + "vector,true_norm", + [ + ((0.0, 0.0, 0.0), 0.0), + ((1.0, 0.0, 0.0), 1.0), + ((0.0, -2.0, 0.0), 2.0), + ((0.0, 0.0, 3.141), 3.141), + (None, None), + ], +) +def test_norm_of_vector(vector, true_norm): + """Computes the norm of a pure vector and compares against a known result.""" + + # If vector is None, randomly sample it + if vector is None: + vector = torch.randn(3) + true_norm = torch.linalg.norm(vector) + + # Construct multivector + inputs = torch.zeros(16) + inputs[2:5] = torch.Tensor(vector) + + # Compute norm + result = norm(inputs) + + # Validate result + true_norm = torch.Tensor([true_norm]) + + torch.testing.assert_close(result, true_norm) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_inner_product_invariance(batch_dims): + """Tests the innner_product() primitive for equivariance.""" + check_pin_invariance(inner_product, 2, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_norm_invariance(batch_dims): + """Tests the norm() primitive for equivariance.""" + check_pin_invariance(norm, 1, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_pin_invariants_invariance(batch_dims): + """Tests the pin_invariants() primitive for equivariance.""" + check_pin_invariance(pin_invariants, 1, batch_dims=batch_dims, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_linear.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..0747a914e0d2bb48cde515e7298ae75d5de2dd84 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_linear.py @@ -0,0 +1,61 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of bilinear primitives.""" + +import pytest +import torch + +from gatr.primitives.linear import ( + NUM_PIN_LINEAR_BASIS_ELEMENTS, + equi_linear, + grade_involute, + grade_project, + reverse, +) +from tests.helpers import ( + BATCH_DIMS, + TOLERANCES, + check_consistence_with_grade_involution, + check_consistence_with_reversal, + check_pin_equivariance, +) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_reverse_correctness(batch_dims): + """Tests the multivector reverse for equivariance.""" + check_consistence_with_reversal(reverse, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_grade_involution_correctness(batch_dims): + """Tests the multivector reverse for equivariance.""" + check_consistence_with_grade_involution(grade_involute, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_identity_equivariance(batch_dims): + """Tests an identity map for equivariance (testing the test).""" + check_pin_equivariance(lambda x: x, 1, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_grade_project_equivariance(batch_dims): + """Tests the grade_project() primitive for equivariance.""" + check_pin_equivariance(grade_project, 1, batch_dims=batch_dims, **TOLERANCES) + + +@pytest.mark.parametrize( + "input_batch_dims,coeff_batch_dims", + [ + ((7,), (5, 7)), + ((3, 7), (5, 7)), + ((2, 3, 7), (5, 7)), + ], +) +def test_linear_equivariance(input_batch_dims, coeff_batch_dims): + """Tests the equi_linear() primitive for equivariance.""" + fn_kwargs = dict(coeffs=torch.randn(*coeff_batch_dims, NUM_PIN_LINEAR_BASIS_ELEMENTS)) + check_pin_equivariance( + equi_linear, 1, fn_kwargs=fn_kwargs, batch_dims=input_batch_dims, **TOLERANCES + ) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_nonlinearities.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_nonlinearities.py new file mode 100644 index 0000000000000000000000000000000000000000..84dbca7f2786727c6e5b753a18d1b136b808e181 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_nonlinearities.py @@ -0,0 +1,27 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of nonlinearity primitives.""" + +import pytest +import torch + +from gatr.primitives import gated_relu, gated_sigmoid +from gatr.primitives.nonlinearities import gated_gelu, gated_gelu_divide +from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("fn", [gated_relu, gated_gelu, gated_sigmoid, gated_gelu_divide]) +@pytest.mark.parametrize("batch_dims", BATCH_DIMS) +def test_gated_nonlin_equivariance(fn, batch_dims): + """Tests an identity map for equivariance (testing the test).""" + gates = torch.randn(*batch_dims, 1) + check_pin_equivariance(fn, 1, fn_kwargs=dict(gates=gates), batch_dims=batch_dims, **TOLERANCES) + + +def test_gelu_division(): + """Test that gated_gelu_divide() is equal to gelu(x)/x.""" + values = torch.randn(2, 3, 4) + gates = torch.randn(2, 3, 4) + y1 = gated_gelu(values, gates) / gates + y2 = gated_gelu_divide(values, gates) + torch.testing.assert_close(y1, y2) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_normalization.py b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fd3f2402cb015c543b6c26282f9f060c6e7c1f --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/primitives/test_normalization.py @@ -0,0 +1,25 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests of nonlinearity primitives.""" + +import pytest +import torch + +from gatr.primitives import equi_layer_norm, norm +from tests.helpers import TOLERANCES, check_pin_equivariance + + +@pytest.mark.parametrize("batch_dims", [(7, 9)]) +@pytest.mark.parametrize("scale", [0.1, 1.0, 50.0]) +def test_equi_layer_norm_correctness(batch_dims, scale): + """Tests whether the output of equi_layer_norm has the correct variance.""" + inputs = scale * torch.randn(*batch_dims, 16) + normalized_inputs = equi_layer_norm(inputs, gain=1.0, epsilon=1e-9) + variance = torch.mean(norm(normalized_inputs) ** 2) + torch.testing.assert_close(variance, torch.ones_like(variance), **TOLERANCES) + + +@pytest.mark.parametrize("batch_dims", [(7, 9)]) +def test_equi_layer_norm_equivariance(batch_dims): + """Tests equi_layer_norm() primitive for equivariance.""" + check_pin_equivariance(equi_layer_norm, 1, batch_dims=batch_dims, **TOLERANCES) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/__init__.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_clifford.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_clifford.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1bffd5b1c358a2c688b791c07dbcf1da9cd524 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_clifford.py @@ -0,0 +1,20 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Unit tests for gatr.utils.ga_clifford.""" + +import pytest +import torch + +from gatr.utils.clifford import mv_list_to_tensor, tensor_to_mv_list + + +@pytest.mark.parametrize("batch_dims", [(1,), (100,), (5, 7), tuple()]) +def test_mv_list_tensor_conversion(batch_dims): + """Tests whether the conversion between lists of clifford.Multivectors and torch.Tensors is + cycle-consistent.""" + + tensor = torch.randn(*batch_dims, 16) + mv_list = tensor_to_mv_list(tensor) + tensor_out = mv_list_to_tensor(mv_list, batch_shape=batch_dims) + + torch.testing.assert_close(tensor_out, tensor) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_compile_linear.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_compile_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd021f63da9441c8cdbc93d2eab47308a00fc44 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_compile_linear.py @@ -0,0 +1,64 @@ +from copy import deepcopy + +import pytest +import torch + +from gatr.layers.linear import EquiLinear +from gatr.layers.mlp.config import MLPConfig +from gatr.layers.mlp.mlp import GeoMLP +from gatr.utils.compile_linear import ( + CompiledLinear, + compile_equi_linear, + compile_equi_linear_submodules, +) + + +@pytest.mark.parametrize("in_s_channels", [6, None]) +@pytest.mark.parametrize("out_s_channels", [8, None]) +@pytest.mark.parametrize("bias", [True, False]) +def test_compile_linear_equivalence(in_s_channels, out_s_channels, bias): + """ + Test equivalence of the EquiLinear and its compiled version. + """ + in_mv_channels = 5 + out_mv_channels = 7 + + equi_linear = EquiLinear( + in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias=bias + ) + compiled_linear = compile_equi_linear(equi_linear) + + in_mv = torch.randn(100, in_mv_channels, 16) + in_s = torch.randn(100, in_s_channels) if in_s_channels is not None else None + + out_mv_equi, out_s_equi = equi_linear(in_mv, in_s) + out_mv_compiled, out_s_compiled = compiled_linear(in_mv, in_s) + + torch.testing.assert_close(out_mv_equi, out_mv_compiled) + torch.testing.assert_close(out_s_equi, out_s_compiled) + + +def test_compilation_substitution(): + """Test in lienar compilation in integration. + + Verify that all EquiLinear submodules are substitued by CompiledLinear. + Verify that the forward pass is equivalent after substitution. + """ + mlp_org = GeoMLP(MLPConfig(mv_channels=[3, 12, 4], s_channels=[2, 12, 5])) + mlp_compiled = deepcopy(mlp_org) + compile_equi_linear_submodules(mlp_compiled) + + assert any(isinstance(m, EquiLinear) for m in mlp_org.modules()) + assert not any(isinstance(m, CompiledLinear) for m in mlp_org.modules()) + assert not any(isinstance(m, EquiLinear) for m in mlp_compiled.modules()) + assert any(isinstance(m, CompiledLinear) for m in mlp_compiled.modules()) + + in_mv = torch.randn(2, 4, 3, 16) + in_s = torch.randn(2, 4, 2) + reference_mv = torch.ones(16) + + out_mv_org, out_s_org = mlp_org(in_mv, in_s, reference_mv=reference_mv) + out_mv_compiled, out_s_compiled = mlp_compiled(in_mv, in_s, reference_mv=reference_mv) + + torch.testing.assert_close(out_mv_org, out_mv_compiled) + torch.testing.assert_close(out_s_org, out_s_compiled) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_dual_basis.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_dual_basis.py new file mode 100644 index 0000000000000000000000000000000000000000..035cdbd62db38f5f92ca251c82aa5587b5d7d5b8 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_dual_basis.py @@ -0,0 +1,18 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import numpy as np +from clifford.pga import layout + +from gatr.utils.dual_basis import compute_dual_basis, dual, point_r3_expand, point_r3_to_mv + + +def test_dual_basis(): + """Tests correctnes sof dual basis.""" + w = compute_dual_basis() + x = layout.MultiVector(np.random.rand(16)) + p_r3 = np.random.rand(3) + p = point_r3_to_mv(p_r3) + p_exp = point_r3_expand(p_r3) + dual1 = dual(p, x).value + dual2 = np.einsum("ijc,c,j->i", w, p_exp, x.value) + np.testing.assert_allclose(dual1, dual2) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_einsum.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..3f1ec39ae302ee1049aebfba5d15244ff1db29c3 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_einsum.py @@ -0,0 +1,65 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from typing import Iterator, Tuple + +import opt_einsum +import pytest +import torch + +from gatr.utils.einsum import cached_einsum + +_DIM = 5 + + +@pytest.fixture(autouse=True, scope="module") +def disable_opt_einsum() -> Iterator[None]: + """Disable usage of opt_einsum by torch during tests in this module.""" + torch.backends.opt_einsum.enabled = False + yield + torch.backends.opt_einsum.enabled = True + + +@pytest.fixture(name="einsum_eq") +def einsum_eq_fixture() -> str: + """Provides a non-trivial einsum equation.""" + # Example equation from https://optimized-einsum.readthedocs.io/en/stable/index.html + return "pi,qj,ijkl,rk,sl->pqrs" + + +@pytest.fixture(name="example_operands") +def example_operands_fixture() -> Tuple[torch.Tensor, ...]: + """Provides tensors for a non-trivial einsum equation.""" + # Example tensors from https://optimized-einsum.readthedocs.io/en/stable/index.html + I = torch.rand(_DIM, _DIM, _DIM, _DIM) + C = torch.rand(_DIM, _DIM) + return (C, C, I, C, C) + + +def test_opt_einsum_shape() -> None: + """Verifies contract_path can be called with shapes. + + Note that we test upstream functionality here, which should not be necessary. + However, with the latest release (3.3.0), this failed. + + NB: Test does not fail on every example (e.g., does not fail on `einsum_eq_fixture`). + We use an equation from a failing test (test_pin). + """ + einsum_eq = "i j k, ... j, ... k -> ... i" + sizes = (_DIM, _DIM, _DIM) + operands = tuple(torch.rand(sizes) for _ in sizes) + op_shape = tuple(x.size() for x in operands) + assert ( + opt_einsum.contract_path(einsum_eq, *operands, optimize="optimal")[0] + == opt_einsum.contract_path(einsum_eq, *op_shape, optimize="optimal", shapes=True)[0] + ) + + +def test_e2e_cached_path(einsum_eq: str, example_operands: Tuple[torch.Tensor]) -> None: + """Checks that torch.einsum and cached_einsum deliver the same values on a non-trivial einsum + equation.""" + expected_result = torch.einsum(einsum_eq, *example_operands) + result_with_uncached_path = cached_einsum(einsum_eq, *example_operands) + result_with_cached_path = cached_einsum(einsum_eq, *example_operands) + + torch.testing.assert_close(expected_result, result_with_uncached_path) + torch.testing.assert_close(expected_result, result_with_cached_path) diff --git a/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_tensors.py b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..e99ba0d28605e99256dc08f5c50f240894273087 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/gatr/utils/test_tensors.py @@ -0,0 +1,45 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.utils.tensors import block_stack, expand_pairwise, to_nd + + +def test_to_nd(): + """Test to_nd.""" + assert to_nd(torch.randn(3), 3).shape == (1, 1, 3) + assert to_nd(torch.randn(2, 3), 3).shape == (1, 2, 3) + assert to_nd(torch.randn(2, 3, 4), 3).shape == (2, 3, 4) + assert to_nd(torch.randn(5, 2, 3, 4), 3).shape == (10, 3, 4) + assert to_nd(torch.randn(3), 4).shape == (1, 1, 1, 3) + assert to_nd(torch.randn(2, 3), 4).shape == (1, 1, 2, 3) + assert to_nd(torch.randn(2, 3, 4), 4).shape == (1, 2, 3, 4) + assert to_nd(torch.randn(5, 2, 3, 4), 4).shape == (5, 2, 3, 4) + assert to_nd(torch.randn(3, 5, 2, 3, 4), 4).shape == (15, 2, 3, 4) + + +def test_expand_pairwise(): + """Test expand pairwise.""" + x = torch.randn(2, 5) + y = torch.randn(3, 2, 1) + z = torch.randn(4, 1, 2, 1) + x2, y2, z2 = expand_pairwise(x, y, z) + assert x2.shape == (4, 3, 2, 5) + assert y2.shape == (4, 3, 2, 5) + assert z2.shape == (4, 3, 2, 5) + + +def test_block_stack(): + """Test block stacking.""" + x = torch.rand(4, 2, 3, 5) + y = torch.rand(4, 4, 5, 5) + z = torch.rand(4, 3, 3, 5) + out = block_stack([x, y, z], 1, 2) + assert list(out.shape) == [4, 9, 11, 5] + torch.testing.assert_close(out[:, 0:2, 0:3, :], x) + torch.testing.assert_close(out[:, 2:6, 3:8, :], y) + torch.testing.assert_close(out[:, 6:9, 8:11, :], z) + out[:, 0:2, 0:3, :] = 0 + out[:, 2:6, 3:8, :] = 0 + out[:, 6:9, 8:11, :] = 0 + torch.testing.assert_close(out, torch.zeros_like(out)) diff --git a/gafl/build/geometric-algebra-transformer/tests/helpers/__init__.py b/gafl/build/geometric-algebra-transformer/tests/helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af94aa781142618177be7c018b385d3811942a55 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/helpers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .constants import BATCH_DIMS, MILD_TOLERANCES, TOLERANCES +from .equivariance import check_pin_equivariance, check_pin_invariance +from .geometric_algebra import ( + check_consistence_with_dual, + check_consistence_with_geometric_product, + check_consistence_with_grade_involution, + check_consistence_with_outer_product, + check_consistence_with_reversal, +) diff --git a/gafl/build/geometric-algebra-transformer/tests/helpers/constants.py b/gafl/build/geometric-algebra-transformer/tests/helpers/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c95c3f06542ac6a0894ca820cf62eda23e949c --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/helpers/constants.py @@ -0,0 +1,10 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Settings used for multiple tests.""" + +# Default tolerances +TOLERANCES = dict(atol=1e-3, rtol=1e-4) +MILD_TOLERANCES = dict(atol=0.05, rtol=0.05) + +# Batch dimensions that are typically checked +BATCH_DIMS = [(7, 9), tuple()] diff --git a/gafl/build/geometric-algebra-transformer/tests/helpers/equivariance.py b/gafl/build/geometric-algebra-transformer/tests/helpers/equivariance.py new file mode 100644 index 0000000000000000000000000000000000000000..50dc47b68297a59d3514e80d3a5f63c292a3dc16 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/helpers/equivariance.py @@ -0,0 +1,148 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Utility functions to test callables for equivariance with respect to Pin(3,0,1).""" + +import torch + +from gatr.utils.clifford import SlowRandomPinTransform + + +def get_first_output(outputs): + """Extracts the first output of a tuple of multiple outputs. + + If only one output is present, returns that. + + This is convenient for equivariance checks: primitives usually just return one multivector + tensor, while layers return two tensors. This function can be wrapped around a callable that's + either a primitive or a layer and will always return the (first) multivector output. + """ + if isinstance(outputs, tuple): + return outputs[0] + + return outputs + + +def check_pin_equivariance( + function, + num_multivector_args=1, + fn_kwargs=None, + batch_dims=(1,), + spin=False, + rng=None, + num_checks=3, + **kwargs, +): + """Checks whether a callable is equivariant with respect to the Pin(3,0,1) or Spin(3,0,1) group. + + The callable can have an arbitray number of multivector inputs. + + Parameters + ---------- + function: Callable + Function to be tested for equivariance. The first `num_multivector_args` positional + arguments need to accept torch.Tensor inputs describing multivectors, and will be + transformed as part of the equivariance test. + num_multivector_args: int + Number of multivector that `function` accepts. + fn_kwargs : dict with str keys + Keyword arguments to call `function` with. + batch_dims : tuple of int + Batch shape for the multivector inputs to `function`. + spin : bool + If True, this function tests Spin equivariance; if False, it tests Pin equivariance. + rng : numpy.random.Generator or None + Numpy rng to draw the inputs and transformations from. + num_checks : int + Number of function calls (with random inputs) to determine whether the function passes the + equivariance test. + kwargs + Optional keyword arguments for the equality check. Will be passed on to np.allclose. + This can for instance be used to specify the absolute and relative tolerance + (by passing `atol` and `rtol` keyword arguments). + """ + # Default arguments + if fn_kwargs is None: + fn_kwargs = {} + + # Propagate numpy random state to torch + if rng is not None: + torch.manual_seed(rng.integers(100000)) + + # Loop over multiple checks + for _ in range(num_checks): + # Generate function inputs and Pin(3,0,1) transformations + inputs = torch.randn(num_multivector_args, *batch_dims, 16) + transform = SlowRandomPinTransform(rng=rng, spin=spin) + + # First function, then transformation + outputs = get_first_output(function(*inputs, **fn_kwargs)) + transformed_outputs = transform(outputs) + + # First transformation, then function + transformed_inputs = transform(inputs) + outputs_of_transformed = get_first_output(function(*transformed_inputs, **fn_kwargs)) + + # Check equality + torch.testing.assert_close(transformed_outputs, outputs_of_transformed, **kwargs) + + +def check_pin_invariance( + function, + num_multivector_args=1, + fn_kwargs=None, + batch_dims=(1,), + spin=False, + rng=None, + num_checks=3, + **kwargs, +): + """Checks whether a callable is invariant with respect to the Pin(3,0,1) or Spin(3,0,1) group. + + Parameters + ---------- + function: Callable + Function to be tested for equivariance. The first `num_multivector_args` positional + arguments need to accept torch.Tensor inputs describing multivectors, and will be + transformed as part of the invariance test. + num_multivector_args: int + Number of multivector that `function` accepts. + fn_kwargs : dict with str keys + Keyword arguments to call `function` with. + batch_dims : tuple of int + Batch shape for the multivector inputs to `function`. + spin : bool + If True, this function tests Spin equivariance; if False, it tests Pin equivariance. + Since Spin is a subgroup of Pin, it is usually enough to confirm Pin equivariance. + rng : numpy.random.Generator or None + Numpy rng to draw the inputs and transformations from. + num_checks : int + Number of function calls (with random inputs) to determine whether the function passes the + equivariance test. + kwargs + Optional keyword arguments for the equality check. Will be passed on to np.allclose. + This can for instance be used to specify the absolute and relative tolerance + (by passing `atol` and `rtol` keyword arguments). + """ + # Default arguments + if fn_kwargs is None: + fn_kwargs = {} + + # Propagate numpy random state to torch + if rng is not None: + torch.manual_seed(rng.integers(100000)) + + # Loop over multiple checks + for _ in range(num_checks): + # Generate function inputs + inputs = torch.randn(num_multivector_args, *batch_dims, 16) + + # Transform inputs with Pin(3,0,1) + transform = SlowRandomPinTransform(rng=rng, spin=spin) + transformed_inputs = transform(inputs) + + # Evaluate function on original and transformed inputs + outputs = get_first_output(function(*inputs, **fn_kwargs)) + outputs_of_transformed = get_first_output(function(*transformed_inputs, **fn_kwargs)) + + # Check equality + torch.testing.assert_close(outputs, outputs_of_transformed, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/tests/helpers/geometric_algebra.py b/gafl/build/geometric-algebra-transformer/tests/helpers/geometric_algebra.py new file mode 100644 index 0000000000000000000000000000000000000000..e52b8108a17964743483d6dbbd62a9b1ba1c516d --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests/helpers/geometric_algebra.py @@ -0,0 +1,113 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""Utility functions to test callables for consistency with clifford algebras.""" + +import clifford +import numpy as np +import torch +from clifford import pga as PGA + +from gatr.utils.clifford import mv_list_to_tensor + + +def _sample_list_of_mv(batch_dims, rng): + """Utility function that samples a list of multivectors.""" + total_batchsize = 1 if not batch_dims else np.product(batch_dims) + xs = clifford.randomMV(layout=PGA.layout, n=total_batchsize, rng=rng) + if total_batchsize == 1: # Dealing with inconsistency of clifford.randomMV + xs = [xs] + return xs + + +def check_consistence_with_geometric_product(function, batch_dims=(1,), rng=None, **kwargs): + """Checks whether a callable computes the geometric product.""" + + # Generate random inputs + xs = _sample_list_of_mv(batch_dims, rng) + ys = _sample_list_of_mv(batch_dims, rng) + + # Compute ground-truth geometric product + xy_true = [(x * y) for x, y in zip(xs, ys)] + xy_true = mv_list_to_tensor(xy_true, batch_dims) + + # Compute geometric product with function + x_tensor = mv_list_to_tensor(xs, batch_dims) + y_tensor = mv_list_to_tensor(ys, batch_dims) + xy = function(x_tensor, y_tensor) + + # Compare + torch.testing.assert_close(xy, xy_true, **kwargs) + + +def check_consistence_with_outer_product(function, batch_dims=(1,), rng=None, **kwargs): + """Checks whether a callable computes the outer product.""" + + # Generate random inputs + xs = _sample_list_of_mv(batch_dims, rng) + ys = _sample_list_of_mv(batch_dims, rng) + + # Compute ground-truth geometric product + xy_true = [(x ^ y) for x, y in zip(xs, ys)] + xy_true = mv_list_to_tensor(xy_true, batch_dims) + + # Compute geometric product with function + x_tensor = mv_list_to_tensor(xs, batch_dims) + y_tensor = mv_list_to_tensor(ys, batch_dims) + xy = function(x_tensor, y_tensor) + + # Compare + torch.testing.assert_close(xy, xy_true, **kwargs) + + +def check_consistence_with_reversal(function, batch_dims=(1,), rng=None, **kwargs): + """Checks whether a callable computes the reversal of a multivector.""" + + # Generate random inputs + xs = _sample_list_of_mv(batch_dims, rng) + + # Compute ground-truth reversal + reversed_x_true = [~x for x in xs] + reversed_x_true = mv_list_to_tensor(reversed_x_true, batch_dims) + + # Compute reversal with function + x_tensor = mv_list_to_tensor(xs, batch_dims) + reversed_x = function(x_tensor) + + # Compare + torch.testing.assert_close(reversed_x, reversed_x_true, **kwargs) + + +def check_consistence_with_grade_involution(function, batch_dims=(1,), rng=None, **kwargs): + """Checks whether a callable computes the grade involution of a multivectors.""" + + # Generate random inputs + xs = _sample_list_of_mv(batch_dims, rng) + + # Compute ground-truth reversal + reversed_x_true = [x.gradeInvol() for x in xs] + reversed_x_true = mv_list_to_tensor(reversed_x_true, batch_dims) + + # Compute reversal with function + x_tensor = mv_list_to_tensor(xs, batch_dims) + reversed_x = function(x_tensor) + + # Compare + torch.testing.assert_close(reversed_x, reversed_x_true, **kwargs) + + +def check_consistence_with_dual(function, batch_dims=(1,), rng=None, **kwargs): + """Checks whether a callable computes the reversal of a multivector.""" + + # Generate random inputs + xs = _sample_list_of_mv(batch_dims, rng) + + # Compute ground-truth reversal + dual_x_true = [x.dual() for x in xs] + dual_x_true = mv_list_to_tensor(dual_x_true, batch_dims) + + # Compute reversal with function + x_tensor = mv_list_to_tensor(xs, batch_dims) + dual_x = function(x_tensor) + + # Compare + torch.testing.assert_close(dual_x, dual_x_true, **kwargs) diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/__init__.py b/gafl/build/geometric-algebra-transformer/tests_regression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03199bcc0b32737d6aa99e611c18c4b81e1b6542 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/__init__.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94936d235ecbd44f21ec36a320d70caac8859bf7 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from .connect_points import ConnectPointsDataset, ConnectPointsWrapper +from .points_distance import PointsDistanceDataset, PointsDistanceWrapper +from .translate_point import TranslatePointDataset, TranslatePointWrapper +from .translation_norm import TranslationNormDataset, TranslationNormWrapper diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/connect_points.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/connect_points.py new file mode 100644 index 0000000000000000000000000000000000000000..6697d2c0528dd162746da399989ce00d6b0f2ad0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/connect_points.py @@ -0,0 +1,110 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_point, extract_translation +from tests_regression.regression_datasets.constants import DATASET_SIZE, DEVICE + + +class ConnectPointsDataset(torch.utils.data.Dataset): + """Toy dataset that maps two points x, y to the translation vector t = y - x between them.""" + + def __init__(self): + super().__init__() + self._inputs = torch.randn((DATASET_SIZE, 2, 3)) + self._target = (self._inputs[:, 1, :] - self._inputs[:, 0, :]).unsqueeze(1) + + # If there's space on the GPU, let's keep the data on the GPU + try: + self._inputs.to(DEVICE) + self._target.to(DEVICE) + except RuntimeError: + pass + + def __len__(self): + """Return number of samples.""" + return len(self._inputs) + + def __getitem__(self, idx): + """Return datapoint.""" + return self._inputs[idx], self._target[idx] + + +class ConnectPointsWrapper(BaseWrapper): + """Wrapper around GATr networks for ConnectPointsDataset.""" + + mv_in_channels = 2 + mv_out_channels = 1 + s_in_channels = 1 + s_out_channels = 1 + raw_in_channels = 3 + raw_out_channels = 3 + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + + batchsize, num_objects, num_features = inputs.shape + assert num_objects == 2 + assert num_features == 3 + + multivector = embed_point(inputs) # (batchsize, 2, 16) + multivector = multivector.unsqueeze(1) # (batchsize, 1, 2, 16) + + # Note that we're encoding the two points as two different *channels*, not two different + # objects. The reason is that an object-permutation-invariant function cannot learn the + # translation vector between two objects (but we have no invariance across channel + # dimensions). + + scalars = torch.zeros((batchsize, 1, 1), device=inputs.device) # (batchsize, 1, 1) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from geometric network. + scalars : torch.Tensor or None + Scalar outputs from geometric network. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + + _, num_objects, num_channels, num_ga_components = multivector.shape + assert num_objects == 1 + assert num_channels == 1 + assert num_ga_components == 16 + + translation = extract_translation( + multivector[:, :, 0, :], divide_by_embedding_dim=False + ) # (batchsize, 1, 3) + + return translation, None diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/constants.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e7fc4d67488de9f996a9b85fb312ca30c2bb3eb2 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/constants.py @@ -0,0 +1,10 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +from gatr.utils.misc import get_device + +BATCHSIZE = 64 +NUM_STEPS = 2000 +STEPS_PER_EPOCH = 100 +DATASET_SIZE = BATCHSIZE * STEPS_PER_EPOCH +NUM_EPOCHS = NUM_STEPS // STEPS_PER_EPOCH +DEVICE = get_device() diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/points_distance.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/points_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba09a1782e00991a091e7173888e3f0c3f186c0 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/points_distance.py @@ -0,0 +1,110 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_point, extract_scalar +from tests_regression.regression_datasets.constants import DATASET_SIZE, DEVICE + + +class PointsDistanceDataset(torch.utils.data.Dataset): + """Toy dataset that maps two points X, Y to the Euclidean distance |X - Y|.""" + + def __init__(self): + super().__init__() + self._inputs = torch.randn((DATASET_SIZE, 2, 3)) + self._target = torch.linalg.norm( + (self._inputs[:, 1, :] - self._inputs[:, 0, :]).unsqueeze(1), dim=-1, keepdim=True + ) + + # If there's space on the GPU, let's keep the data on the GPU + try: + self._inputs.to(DEVICE) + self._target.to(DEVICE) + except RuntimeError: + pass + + def __len__(self): + """Return number of samples.""" + return len(self._inputs) + + def __getitem__(self, idx): + """Return datapoint.""" + return self._inputs[idx], self._target[idx] + + +class PointsDistanceWrapper(BaseWrapper): + """Wrapper around GATr networks for PointsDistanceDataset.""" + + mv_in_channels = 2 + mv_out_channels = 1 + s_in_channels = 1 + s_out_channels = 1 + raw_in_channels = 3 + raw_out_channels = 1 + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + + batchsize, num_objects, num_features = inputs.shape + assert num_objects == 2 + assert num_features == 3 + + multivector = embed_point(inputs) # (batchsize, 2, 16) + multivector = multivector.unsqueeze(1) # (batchsize, 1, 2, 16) + + # Note that we're encoding the two points as two different *channels*, not two different + # objects. The reason is that an object-permutation-invariant function cannot learn the + # translation vector between two objects (but we have no invariance across channel + # dimensions). + + scalars = torch.zeros((batchsize, 1, 1), device=inputs.device) # (batchsize, 1, 1) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from geometric network. + scalars : torch.Tensor or None + Scalar outputs from geometric network. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + + _, num_objects, num_channels, num_ga_components = multivector.shape + assert num_objects == 1 + assert num_channels == 1 + assert num_ga_components == 16 + + norm = extract_scalar(multivector[:, :, 0, :]) # (batchsize, 1, 3) + + return norm, None diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translate_point.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translate_point.py new file mode 100644 index 0000000000000000000000000000000000000000..aea5b575d678d51d7622aa832d27fa2d0a4a3a3b --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translate_point.py @@ -0,0 +1,109 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_point, embed_translation, extract_point +from tests_regression.regression_datasets.constants import DATASET_SIZE, DEVICE + + +class TranslatePointDataset(torch.utils.data.Dataset): + """Toy dataset that maps a point x and a translation vector t to the translated point t+x.""" + + def __init__(self): + super().__init__() + self._point = torch.randn((DATASET_SIZE, 1, 3)) + self._translation = torch.randn((DATASET_SIZE, 1, 3)) + self._inputs = torch.cat((self._point, self._translation), dim=2) + self._target = self._point + self._translation + + # If there's space on the GPU, let's keep the data on the GPU + try: + self._inputs.to(DEVICE) + self._target.to(DEVICE) + except RuntimeError: + pass + + def __len__(self): + """Return number of samples.""" + return len(self._inputs) + + def __getitem__(self, idx): + """Return datapoint.""" + return self._inputs[idx], self._target[idx] + + +class TranslatePointWrapper(BaseWrapper): + """Wrapper around GATr networks for TranslatePointDataset.""" + + mv_in_channels = 1 + mv_out_channels = 1 + s_in_channels = 1 + s_out_channels = 1 + raw_in_channels = 6 + raw_out_channels = 3 + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + + batchsize, num_objects, num_features = inputs.shape + assert num_objects == 1 + assert num_features == 6 + + points = inputs[:, :, :3] # (batchsize, 1, 3) + points = embed_point(points) # (batchsize, 1, 16) + translation = inputs[:, :, 3:] # (batchsize, 1, 3) + translation = embed_translation(translation) # (batchsize, 1, 16) + multivector = points + translation # (batchsize, 1, 16) + multivector = multivector.unsqueeze(2) # (batchsize, 1, 1, 16) + + scalars = torch.zeros((batchsize, num_objects, 1), device=inputs.device) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from geometric network. + scalars : torch.Tensor or None + Scalar outputs from geometric network. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + + _, num_objects, num_channels, num_ga_components = multivector.shape + assert num_objects == 1 + assert num_channels == 1 + assert num_ga_components == 16 + + point = extract_point(multivector[:, :, 0, :]) # (batchsize, 1, 3) + + return point, None diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translation_norm.py b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translation_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..d800100f5cf05556e202f1eee20ed71506f4c637 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/regression_datasets/translation_norm.py @@ -0,0 +1,106 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +import torch + +from gatr.experiments.base_wrapper import BaseWrapper +from gatr.interface import embed_point, embed_translation, extract_scalar +from tests_regression.regression_datasets.constants import DATASET_SIZE, DEVICE + + +class TranslationNormDataset(torch.utils.data.Dataset): + """Toy dataset that maps a translation vector t to its Euclidean norm |t|.""" + + def __init__(self): + super().__init__() + self._inputs = torch.randn((DATASET_SIZE, 2, 3)) + self._target = torch.linalg.norm(self._inputs[..., [0], :], dim=-1, keepdim=True) + + # If there's space on the GPU, let's keep the data on the GPU + try: + self._inputs.to(DEVICE) + self._target.to(DEVICE) + except RuntimeError: + pass + + def __len__(self): + """Return number of samples.""" + return len(self._inputs) + + def __getitem__(self, idx): + """Return datapoint.""" + return self._inputs[idx], self._target[idx] + + +class TranslationNormWrapper(BaseWrapper): + """Wrapper around GATr networks for TranslationNormDataset.""" + + mv_in_channels = 2 + mv_out_channels = 1 + s_in_channels = 1 + s_out_channels = 1 + raw_in_channels = 6 + raw_out_channels = 1 + + def __init__(self, net): + super().__init__(net, scalars=True, return_other=False) + + def embed_into_ga(self, inputs): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + inputs : torch.Tensor + Raw inputs, as given by dataset. + + Returns + ------- + mv_inputs : torch.Tensor + Multivector inputs, as expected by geometric network. + scalar_inputs : torch.Tensor or None + Scalar inputs, as expected by geometric network. + """ + + batchsize, num_objects, num_features = inputs.shape + assert num_objects == 2 + assert num_features == 3 + + translation = embed_translation(inputs[..., [0], :]) # (batchsize, 1, 16) + reference = embed_point(inputs[..., [1], :]) # (batchsize, 1, 16) + multivector = torch.cat([translation, reference], dim=1).unsqueeze( + 1 + ) # (batchsize, 1, 2, 16) + + scalars = torch.zeros((batchsize, 1, 1), device=inputs.device) # (batchsize, 1, 1) + + return multivector, scalars + + def extract_from_ga(self, multivector, scalars): + """Embeds raw inputs into the geometric algebra (+ scalar) representation. + + To be implemented by subclasses. + + Parameters + ---------- + multivector : torch.Tensor + Multivector outputs from geometric network. + scalars : torch.Tensor or None + Scalar outputs from geometric network. + + Returns + ------- + outputs : torch.Tensor + Raw outputs, as expected in dataset. + other : torch.Tensor + Additional output data, e.g. required for regularization. + """ + + _, num_objects, num_channels, num_ga_components = multivector.shape + assert num_objects == 1 + assert num_channels == 1 + assert num_ga_components == 16 + + norm = extract_scalar(multivector[:, :, 0, :]) # (batchsize, 1, 3) + + return norm, None diff --git a/gafl/build/geometric-algebra-transformer/tests_regression/test_regression.py b/gafl/build/geometric-algebra-transformer/tests_regression/test_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..89ba34a158bd4c1b76dd159362c2af56c391d544 --- /dev/null +++ b/gafl/build/geometric-algebra-transformer/tests_regression/test_regression.py @@ -0,0 +1,68 @@ +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# All rights reserved. +"""A regression test that tests regression.""" + +import pytest +import torch +from tqdm import trange + +from gatr.layers.attention.config import SelfAttentionConfig +from gatr.layers.mlp.config import MLPConfig +from gatr.nets import GATr +from tests_regression.regression_datasets.constants import BATCHSIZE, DEVICE, NUM_EPOCHS +from tests_regression.regression_datasets.points_distance import ( + PointsDistanceDataset, + PointsDistanceWrapper, +) + + +def gatr_factory(wrapper_class): + """Factory function for a GATr model.""" + print("Creating GATr") + model = GATr( + in_mv_channels=wrapper_class.mv_in_channels, + out_mv_channels=wrapper_class.mv_out_channels, + hidden_mv_channels=8, + in_s_channels=wrapper_class.s_in_channels, + out_s_channels=wrapper_class.s_out_channels, + hidden_s_channels=16, + attention=SelfAttentionConfig( + num_heads=4, + increase_hidden_channels=2, + multi_query=True, + ), + num_blocks=10, + mlp=MLPConfig(), + ) + wrapped_model = wrapper_class(model) + return wrapped_model + + +@pytest.mark.parametrize("model_factory", [gatr_factory], ids=["GATr"]) +@pytest.mark.parametrize( + "data,wrapper_class", [(PointsDistanceDataset(), PointsDistanceWrapper)], ids=["distance"] +) +def test_regression(model_factory, data, wrapper_class, lr=3e-4, target_loss=0.1): + """Test whether model can successfully regress on a dataset data to almost zero train error.""" + + model = model_factory(wrapper_class) + dataloader = torch.utils.data.DataLoader(data, batch_size=BATCHSIZE, shuffle=True) + optim = torch.optim.Adam(model.parameters(), lr=lr) + criterion = torch.nn.MSELoss() + model = model.to(DEVICE) + + print("Starting training") + for _ in (pbar := trange(NUM_EPOCHS)): + epoch_loss = 0.0 + for x, y in dataloader: + x, y = x.to(DEVICE), y.to(DEVICE) + y_pred = model(x) + loss = criterion(y_pred, y) + optim.zero_grad() + loss.backward() + optim.step() + epoch_loss += loss.item() / len(dataloader) + pbar.set_description(desc=f"Loss = {loss.item():.3f}", refresh=True) + + print(f"Training loss in last epoch: {epoch_loss}") + assert epoch_loss < target_loss diff --git a/gafl/configs/data/default.yaml b/gafl/configs/data/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0f4ecd2fa2d24cf45c1aafe092b44daeda5adf81 --- /dev/null +++ b/gafl/configs/data/default.yaml @@ -0,0 +1,34 @@ +dataset: + seed: 123 + max_num_res: 128 + cache_num_res: 0 + min_num_res: 0 + subset: null + generate_valid_samples: True # Determines if validation samples should be generated # Logically makes more sense in the experiment config -> Find a way to shift it there + samples_per_eval_length: 5 + num_eval_lengths: 8 + min_eval_length: 500 + train_valid_test_split: [1.0, 0.0, 0.0] + csv_path: + cluster_path_framediff: null + filter_breaks: False + label_breaks: False + use_res_idx: False + scrmsd_csv_path: null + filter_scrmsd: inf + calc_dssp: False + max_coil_pct: 1. + allowed_oligomers: [monomeric] + target_sec_content: + helix_percent: 0.39 + strand_percent: 0.21 + apply_clustering: False + +loader: + num_workers: 4 + prefetch_factor: 10 + +sampler: + max_batch_size: 100 + max_num_res_squared: 500_000 + clustered: ${data.dataset.apply_clustering} diff --git a/gafl/configs/data/pdb.yaml b/gafl/configs/data/pdb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4baa3d7d000115d0a0e1ba61a7242d43f51ffbd7 --- /dev/null +++ b/gafl/configs/data/pdb.yaml @@ -0,0 +1,29 @@ +defaults: + - default + +dataset: + seed: 123 + max_num_res: 512 + cache_num_res: 0 + min_num_res: 0 + samples_per_eval_length: 10 + num_eval_lengths: 5 + min_num_res_eval: 100 + min_eval_length: 300 + csv_path: + cluster_path_framediff: + break_csv_path: null + filter_breaks: False + label_breaks: True + use_res_idx: True + filter_scrmsd: inf + max_coil_pct: 0.5 + allowed_oligomers: [monomeric] + calc_dssp: True + train_valid_test_split: [1., 0., 0.] + apply_clustering: True + +sampler: + max_batch_size: 100 + max_num_res_squared: 500_000 + clustered: ${data.dataset.apply_clustering} \ No newline at end of file diff --git a/gafl/configs/experiment/default.yaml b/gafl/configs/experiment/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e35a3cda2ab89820b6a7db69ed23a883eedeecd --- /dev/null +++ b/gafl/configs/experiment/default.yaml @@ -0,0 +1,70 @@ +debug: False +use_wandb: True +use_tqdm: True + +seed: 123 +num_devices: 2 +warm_start: null +warm_start_cfg_override: True +use_swa: False +first_val_epoch: 0 +batch_ot: + enabled: True + cost: kabsch + noise_per_sample: 1 +training: + min_plddt_mask: null + loss: se3_vf_loss + bb_atom_scale: 0.1 + trans_scale: 0.1 + translation_loss_weight: 2.0 + t_normalize_clip: 0.9 + rotation_loss_weights: 1.0 + aux_loss_weight: 1.0 + aux_loss_t_pass: 0.25 + t_bins: 4 +wandb: + name: gafl + project: protein-flow-matching + save_dir: outputs/ + # save_code: True + tags: [] +optimizer: + lr: 0.0001 +scheduler: + enabled: False + warmup_lr: 0.00001 + lr_min: 0.00005 + warmup_epochs: 10 + constant_epochs: 100 + min_epoch: 200 +reset_optimizer_on_load: False +trainer: + overfit_batches: 0 + min_epochs: 1 # prevents early stopping + max_epochs: 5000 + accelerator: gpu + log_every_n_steps: 1 + deterministic: False + strategy: ddp + check_val_every_n_epoch: 20 + default_root_dir: outputs/ + accumulate_grad_batches: 1 +checkpointer: + dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S-%f} + save_last: True + filename: "epoch:{epoch:03d}" + every_n_epochs: 200 + save_top_k: -1 + auto_insert_metric_name: False + save_on_train_epoch_end: True +checkpointer2: + dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} + save_last: False + filename: "sec_dev:{sec_deviation:.2f}-epoch:{epoch:03d}" + save_top_k: 10 + monitor: valid/sec_deviation + mode: min + every_n_epochs: ${experiment.trainer.check_val_every_n_epoch} + first_epoch: ${experiment.first_val_epoch} + auto_insert_metric_name: False diff --git a/gafl/configs/experiment/pdb.yaml b/gafl/configs/experiment/pdb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..668aef08827cdce88552393e9e8571ea5e213ce5 --- /dev/null +++ b/gafl/configs/experiment/pdb.yaml @@ -0,0 +1,39 @@ +defaults: + - default + - _self_ + +debug: False +use_tqdm: False + +warm_start: null +warm_start_cfg_override: True +first_val_epoch: 2000 +wandb: + name: gafl + project: gafl-pdb + save_dir: outputs/ +trainer: + min_epochs: 1 # prevents early stopping + max_epochs: 100000 + check_val_every_n_epoch: 2 +checkpointer: + every_n_epochs: 50 +checkpointer2: + first_epoch: ${experiment.first_val_epoch} + save_top_k: 20 + every_n_epochs: ${experiment.trainer.check_val_every_n_epoch} + +reset_optimizer_on_load: False +optimizer: + lr: 0.00025 +scheduler: + enabled: True + warmup_lr: 0.00001 + lr_min: 0.0001 + warmup_epochs: 20 + constant_epochs: 1500 + min_epoch: 2000 + +training: + aux_loss_t_pass: 0.75 + aux_loss_weight: 1. \ No newline at end of file diff --git a/gafl/configs/inference.yaml b/gafl/configs/inference.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d61ff66281c8ce868332c82f66f00475e4a7d4b6 --- /dev/null +++ b/gafl/configs/inference.yaml @@ -0,0 +1,57 @@ +defaults: + - _self_ + +hydra: + run: + dir: outputs/hydra/ + +inference: + # Use this to write with date-time stamp. + name: run_${now:%Y-%m-%d}_${now:%H-%M-%S-%f} + seed: 123 + ckpt_path: + output_dir: outputs/inference/ + + use_gpu: True + num_gpus: 2 + + interpolant: + min_t: 1e-2 + rots: + corrupt: True + sample_schedule: exp + exp_rate: 10 + trans: + corrupt: True + sample_schedule: linear + sampling: + num_timesteps: 200 + self_condition: True + noise_res_scaling_power: 0.0 + noise_scale: 1. + + samples: + + # Number of backbone samples per sequence length. + samples_per_length: 10 + + # Batch size for sampling. + batch_size: 10 + + # Number of ESMFfold samples per backbone sample. + seq_per_sample: 8 + + # Minimum sequence length to sample. + min_length: 100 + + # Maximum sequence length to sample. + max_length: 300 + + # gap between lengths to sample. i.e. this script will sample all lengths + # in range(min_length, max_length, length_step) + length_step: 100 + + # Subset of lengths to sample. If null, sample all targets. + length_subset: null + + overwrite: False diff --git a/gafl/configs/interpolant/default.yaml b/gafl/configs/interpolant/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4425e7688b29d4c4a887035a02d5033353d32249 --- /dev/null +++ b/gafl/configs/interpolant/default.yaml @@ -0,0 +1,16 @@ +min_t: 1e-2 +t_interval: [0.0, 1.0] # Determines the range of t values to sample from during training +rots: + train_schedule: linear + sample_schedule: exp + exp_rate: 10 +trans: + train_schedule: linear + sample_schedule: linear +sampling: + num_timesteps: 100 +self_condition: ${model.edge_features.self_condition} +noise_res_scaling_power: 0.0 +noise_scale: 1. + +t_sampling_focus: 0.0 \ No newline at end of file diff --git a/gafl/configs/interpolant/pdb.yaml b/gafl/configs/interpolant/pdb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6607dad35a0ee6784ce51748bbd78cc5f7e38273 --- /dev/null +++ b/gafl/configs/interpolant/pdb.yaml @@ -0,0 +1,16 @@ +min_t: 1e-2 +t_interval: [0.0, 1.0] # Determines the range of t values to sample from during training +rots: + train_schedule: linear + sample_schedule: exp + exp_rate: 10 +trans: + train_schedule: linear + sample_schedule: linear +sampling: + num_timesteps: 100 +self_condition: ${model.edge_features.self_condition} +noise_res_scaling_power: 0. +noise_scale: 1. + +t_sampling_focus: 0.6 \ No newline at end of file diff --git a/gafl/configs/model/default.yaml b/gafl/configs/model/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e49bbf7af90869e396efc6576a0dfcd30c41a6da --- /dev/null +++ b/gafl/configs/model/default.yaml @@ -0,0 +1,4 @@ +node_features: + embed_breaks: True +edge_features: + embed_breaks: True \ No newline at end of file diff --git a/gafl/configs/model/frameflow.yaml b/gafl/configs/model/frameflow.yaml new file mode 100644 index 0000000000000000000000000000000000000000..06967a9f394334333dd93b621c4a9af71a612389 --- /dev/null +++ b/gafl/configs/model/frameflow.yaml @@ -0,0 +1,34 @@ +defaults: + - default + +module: models.flow_model.FlowModel +node_embed_size: 256 +edge_embed_size: 128 +symmetric: False +node_features: + c_s: ${model.node_embed_size} + c_pos_emb: 128 + c_timestep_emb: 128 + embed_diffuse_mask: False + max_num_res: 2000 + timestep_int: 1000 +edge_features: + single_bias_transition_n: 2 + c_s: ${model.node_embed_size} + c_p: ${model.edge_embed_size} + relpos_k: 64 + use_rbf: True + num_rbf: 32 + feat_dim: 64 + num_bins: 22 + self_condition: True +ipa: + c_s: ${model.node_embed_size} + c_z: ${model.edge_embed_size} + c_hidden: 128 + no_heads: 8 + no_qk_points: 8 + no_v_points: 12 + seq_tfmr_num_heads: 4 + seq_tfmr_num_layers: 2 + num_blocks: 6 \ No newline at end of file diff --git a/gafl/configs/model/gafl.yaml b/gafl/configs/model/gafl.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8293693c027aece527575640fd813171f089a175 --- /dev/null +++ b/gafl/configs/model/gafl.yaml @@ -0,0 +1,36 @@ +defaults: + - default + +module: models.gafl.flow_model.FlowModel +node_embed_size: 240 +edge_embed_size: 120 +symmetric: False +node_features: + c_s: ${model.node_embed_size} + c_pos_emb: 120 + c_timestep_emb: 120 + embed_diffuse_mask: False + max_num_res: 2000 + timestep_int: 1000 + embed_breaks: True +edge_features: + single_bias_transition_n: 2 + c_s: ${model.node_embed_size} + c_p: ${model.edge_embed_size} + relpos_k: 64 + use_rbf: True + num_rbf: 32 + feat_dim: 64 + num_bins: 22 + self_condition: True + embed_breaks: True +gfa: + c_s: ${model.node_embed_size} + c_z: ${model.edge_embed_size} + c_hidden: 120 + no_heads: 8 + no_qk_points: 8 + no_v_points: 8 + seq_tfmr_num_heads: 4 + seq_tfmr_num_layers: 2 + num_blocks: 6 \ No newline at end of file diff --git a/gafl/configs/train_frameflow_pdb.yaml b/gafl/configs/train_frameflow_pdb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9aab5c738d63ded8ebfe7db4507de9ed4900c110 --- /dev/null +++ b/gafl/configs/train_frameflow_pdb.yaml @@ -0,0 +1,38 @@ +defaults: + - data: pdb + - experiment: pdb + - interpolant: pdb + - model: frameflow + - _self_ + +hydra: + run: + dir: outputs/hydra/ + +experiment: + seed: 123 + first_val_epoch: 5000 + wandb: + name: frameflow-pdb + trainer: + max_epochs: 5200 + check_val_every_n_epoch: 2 + checkpointer: + every_n_epochs: 50 + checkpointer2: + first_epoch: ${experiment.first_val_epoch} + save_top_k: 30 + every_n_epochs: ${experiment.trainer.check_val_every_n_epoch} + optimizer: + lr: 0.0002 + scheduler: + enabled: True + warmup_lr: 0.00004 + lr_min: 0.0001 + warmup_epochs: 50 + constant_epochs: 3500 + min_epoch: 5000 + +data: + dataset: + seed: 123 \ No newline at end of file diff --git a/gafl/configs/train_gafl_pdb.yaml b/gafl/configs/train_gafl_pdb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5d7132fe94ab8cb3aaefd2d773f989a920e20a2 --- /dev/null +++ b/gafl/configs/train_gafl_pdb.yaml @@ -0,0 +1,36 @@ +defaults: + - data: pdb + - experiment: pdb + - interpolant: pdb + - model: gafl + - _self_ + +hydra: + run: + dir: outputs/hydra/ + +experiment: + seed: 123 + first_val_epoch: 5000 + trainer: + max_epochs: 5200 + check_val_every_n_epoch: 2 + checkpointer: + every_n_epochs: 50 + checkpointer2: + first_epoch: ${experiment.first_val_epoch} + save_top_k: 30 + every_n_epochs: ${experiment.trainer.check_val_every_n_epoch} + optimizer: + lr: 0.0002 + scheduler: + enabled: True + warmup_lr: 0.00004 + lr_min: 0.0001 + warmup_epochs: 50 + constant_epochs: 3500 + min_epoch: 5000 + +data: + dataset: + seed: 123 \ No newline at end of file diff --git a/gafl/configs/train_se3_flows.yaml b/gafl/configs/train_se3_flows.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6f9b064377bbb8d00b5eace6082aabbdcc2074c6 --- /dev/null +++ b/gafl/configs/train_se3_flows.yaml @@ -0,0 +1,10 @@ +defaults: + - data: default + - experiment: default + - interpolant: default + - model: gafl + - _self_ + +hydra: + run: + dir: outputs/hydra/ \ No newline at end of file diff --git a/gafl/environment.yaml b/gafl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3aea02ed8d2e896252bb1ade2b7be83106b832d0 --- /dev/null +++ b/gafl/environment.yaml @@ -0,0 +1,51 @@ +name: gafl +channels: + - pytorch + - nvidia + - pyg + - conda-forge +dependencies: + - python=3.10 + - pip + - setuptools<81 # lightning 1.9.5 still uses pkg_resources + - pytorch=2.1.2=py3.10_cuda12.1_cudnn8.9.2_0 + - pytorch-cuda=12.1 + - pytorch-mutex=1.0=cuda + - pytorch-scatter=2.1.2=py310_torch_2.1.0_cu121 + - numpy=1.26.* + - pandas + - scipy + - scikit-learn + - tqdm + - biopython + - biotite + - mdtraj + - tmtools + - openmm + - pdbfixer + - dm-tree + - pip: + - absl-py==2.1.0 + - hydra-core==1.3.2 + - omegaconf==2.3.0 + - ml-collections==0.1.1 + - GPUtil==1.4.0 + - wandb==0.16.4 + - einops==0.7.0 + - opt-einsum==3.4.0 + - pytorch-lightning==1.9.5 + - torchmetrics==1.1.2 + - matplotlib==3.7.3 + - seaborn==0.13.2 + - MDAnalysis==2.7.0 + - hjson + - ipython + # optional analysis / openfold dependencies (kept to avoid future dep + # conflicts even though the basic inference/train commands don't need them) + - fair-esm==2.0.0 # used by gafl/analysis/sc_dataset.py + - deepspeed==0.14.5 # required by openfold/{model,utils}; >=0.18 needs torch>=2.4 + - git+https://github.com/NVIDIA/dllogger.git # imported by openfold/utils/logger.py + # gafl itself (run from repo root): + # pip install -e . + # gatr (patched fork of qualcomm-ai-research/geometric-algebra-transformer): + # bash install_gatr.sh diff --git a/gafl/experiments/__init__.py b/gafl/experiments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/experiments/inference.py b/gafl/experiments/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..b64499280fe8a3b47b0785b9d6639b2c9b40ca85 --- /dev/null +++ b/gafl/experiments/inference.py @@ -0,0 +1,123 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""DDP inference script.""" +import os +import time +import numpy as np +import hydra +import torch +import GPUtil +from pytorch_lightning import Trainer +from omegaconf import DictConfig, OmegaConf +from pathlib import Path + +from gafl.models.flow_module import FlowModule +from gafl import experiment_utils as eu + + + +torch.set_float32_matmul_precision('high') +log = eu.get_pylogger(__name__) + +class Sampler: + + def __init__(self, cfg: DictConfig): + """Initialize sampler. + + Args: + cfg: inference config. + """ + ckpt_path = cfg.inference.ckpt_path + ckpt_dir = os.path.dirname(ckpt_path) + ckpt_cfg = OmegaConf.load(os.path.join(ckpt_dir, 'config.yaml')) + + # Set-up config. + OmegaConf.set_struct(cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg, ckpt_cfg) + cfg.experiment.checkpointer.dirpath = './' + + self._cfg = cfg + self._infer_cfg = cfg.inference + self._samples_cfg = self._infer_cfg.samples + self._rng = np.random.default_rng(self._infer_cfg.seed) + + # Set-up directories to write results to + self._ckpt_name = '/'.join(ckpt_path.replace('.ckpt', '').split('/')[-3:]) + self._output_dir = os.path.join( + self._infer_cfg.output_dir, + self._ckpt_name, + self._infer_cfg.name, + ) + os.makedirs(self._output_dir, exist_ok=True) + self.config_path = os.path.join(self._output_dir, 'config.yaml') + with open(self.config_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f) + + # Read checkpoint and initialize module. + self._flow_module = FlowModule.load_from_checkpoint( + checkpoint_path=ckpt_path, + ) + self._flow_module.eval() + self._flow_module._infer_cfg = self._infer_cfg + if not hasattr(self._infer_cfg, 'max_res_per_esm_batch'): + self._infer_cfg.max_res_per_esm_batch = 2056 + self._flow_module._samples_cfg = self._samples_cfg + self._flow_module._output_dir = self._output_dir + + def run_sampling(self): + devices = GPUtil.getAvailable( + order='memory', limit = 8)[:self._infer_cfg.num_gpus] + log.info(f"Using devices: {devices}") + # eval_dataset = eu.LengthDataset(self._samples_cfg) + eval_dataset = eu.LengthDatasetBatch(self._samples_cfg) + dataloader = torch.utils.data.DataLoader( + eval_dataset, batch_size=1, shuffle=False, drop_last=False) + trainer = Trainer( + accelerator="gpu", + strategy="ddp", + devices=devices, + ) + self._log_information_on_start() + trainer.predict(self._flow_module, dataloaders=dataloader) + + def _log_information_on_start(self): + min_len = self._samples_cfg.min_length + max_len = self._samples_cfg.max_length + samples_per_length = self._samples_cfg.samples_per_length + length_step = self._samples_cfg.length_step + num_timesteps = self._infer_cfg.interpolant.sampling.num_timesteps + + sampled_lengths = list(range(min_len, max_len + 1, length_step)) + + MAX_PRINTED_LENS = 5 + if len(sampled_lengths) <= MAX_PRINTED_LENS: + sampled_len_str = '[' + ', '.join(map(str, sampled_lengths)) + ']' + else: + sampled_len_str = '[' + ', '.join(map(str, sampled_lengths[:MAX_PRINTED_LENS-1])) + ', ..., ' + str(sampled_lengths[-1]) + ']' + + logstr = f'\n\nSAMPLING CONFIG:\n{"="*80}' + logstr += f'\nSaving results to {self._output_dir}' + logstr += f'\nNumber of timesteps: {num_timesteps}' + logstr += f'\nGenerating {samples_per_length} samples for each length in {sampled_len_str}' + logstr += f'\n{"="*80}\n' + + log.info(logstr) + + +@hydra.main(version_base=None, config_path="../configs", config_name="inference") +def run(cfg: DictConfig) -> None: + + # Read model checkpoint. + log.info(f'Starting inference with {cfg.inference.num_gpus} GPUs') + start_time = time.time() + sampler = Sampler(cfg) + sampler.run_sampling() + elapsed_time = time.time() - start_time + + log.info(f'Finished in {elapsed_time:.2f}s') + +if __name__ == '__main__': + run() diff --git a/gafl/experiments/train.py b/gafl/experiments/train.py new file mode 100644 index 0000000000000000000000000000000000000000..9118cd96104bde9b7b7f735d1cff549d1c6a9a46 --- /dev/null +++ b/gafl/experiments/train.py @@ -0,0 +1,138 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import os +import GPUtil +import torch + +import hydra +from omegaconf import DictConfig, OmegaConf + +# Pytorch lightning imports +from pytorch_lightning import LightningDataModule, LightningModule, Trainer +from pytorch_lightning.loggers.wandb import WandbLogger +from pytorch_lightning.trainer import Trainer +from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor +import wandb + +from gafl.data.pdb_dataloader import PdbDataModule +from gafl.experiment_utils import EpochModelCheckpoint +from gafl.models.flow_module import FlowModule +from gafl import experiment_utils as eu + +log = eu.get_pylogger(__name__) +torch.set_float32_matmul_precision('high') +class Experiment: + + def __init__(self, *, cfg: DictConfig): + self._cfg = cfg + self._data_cfg = cfg.data + self._exp_cfg = cfg.experiment + + #Handle missing experiment configs elements + OmegaConf.set_struct(self._exp_cfg, False) + if not hasattr(self._exp_cfg.training, 't_bins'): + self._exp_cfg.training.t_bins = 4 + + OmegaConf.set_struct(self._exp_cfg, True) + + self.create_data_module() + self.create_module() + + def create_module(self): + self._model: LightningModule = FlowModule(self._cfg) + + def create_data_module(self): + self._datamodule: LightningDataModule = PdbDataModule(self._data_cfg) + + def train(self): + callbacks = [] + if self._exp_cfg.debug: + log.info("Debug mode.") + logger = None + self._exp_cfg.num_devices = 1 + self._data_cfg.loader.num_workers = 0 + else: + if self._exp_cfg.use_wandb: + logger = WandbLogger( + **self._exp_cfg.wandb, + ) + else: + logger = None + + # Checkpoint directory. + ckpt_dir = self._exp_cfg.checkpointer.dirpath + os.makedirs(ckpt_dir, exist_ok=True) + log.info(f"Checkpoints saved to {ckpt_dir}") + + # Model checkpoints + callbacks.append(ModelCheckpoint(**self._exp_cfg.checkpointer)) + + if 'checkpointer2' in self._exp_cfg: + ckpt_dir2 = self._exp_cfg.checkpointer2.dirpath + os.makedirs(ckpt_dir2, exist_ok=True) + log.info(f"Additional Checkpoints saved to {ckpt_dir2}") + callbacks.append(EpochModelCheckpoint(**self._exp_cfg.checkpointer2)) + if 'first_val_epoch' not in self._exp_cfg: + callbacks.append(eu.ValidationCallback(self._exp_cfg.checkpointer2.first_epoch)) + elif self._exp_cfg.first_val_epoch > self._exp_cfg.checkpointer2.first_epoch: + # Log warning + log.warning("First validation epoch is greater than the first checkpoint epoch. Setting first validation epoch to first checkpoint epoch.") + callbacks.append(eu.ValidationCallback(self._exp_cfg.checkpointer2.first_epoch)) + else: + callbacks.append(eu.ValidationCallback(self._exp_cfg.first_val_epoch)) + + if self._exp_cfg.scheduler.enabled and logger is not None: + lr_monitor = LearningRateMonitor(logging_interval='epoch') + callbacks.append(lr_monitor) + + # Save config + cfg_path = os.path.join(ckpt_dir, 'config.yaml') + with open(cfg_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f.name) + cfg_dict = OmegaConf.to_container(self._cfg, resolve=True) + flat_cfg = dict(eu.flatten_dict(cfg_dict)) + if self._exp_cfg.use_wandb and isinstance(logger.experiment.config, wandb.sdk.wandb_config.Config): + logger.experiment.config.update(flat_cfg) + + devices = GPUtil.getAvailable(order='memory', limit = 8)[:self._exp_cfg.num_devices] + log.info(f"Using devices: {devices}") + + trainer = Trainer( + **self._exp_cfg.trainer, + callbacks=callbacks, + logger=logger, + replace_sampler_ddp=False, # in later versions of pytorch lightning, this is called use_distributed_sampler + enable_progress_bar=self._exp_cfg.use_tqdm, + enable_model_summary=True, + devices=devices, + ) + trainer.fit( + model=self._model, + datamodule=self._datamodule, + ckpt_path=self._exp_cfg.warm_start + ) + +@hydra.main(version_base=None, config_path="../configs", config_name="train_se3_flows.yaml") +def main(cfg: DictConfig): + + if cfg.experiment.warm_start is not None and cfg.experiment.warm_start_cfg_override: + # Loads warm start config. + warm_start_cfg_path = os.path.join( + os.path.dirname(cfg.experiment.warm_start), 'config.yaml') + warm_start_cfg = OmegaConf.load(warm_start_cfg_path) + + # Warm start config may not have latest fields in the base config. + # Add these fields to the warm start config. + OmegaConf.set_struct(cfg.model, False) + OmegaConf.set_struct(warm_start_cfg.model, False) + cfg.model = OmegaConf.merge(cfg.model, warm_start_cfg.model) + OmegaConf.set_struct(cfg.model, True) + log.info(f'Loaded warm start config from {warm_start_cfg_path}') + + exp = Experiment(cfg=cfg) + exp.train() + +if __name__ == "__main__": + main() diff --git a/gafl/gafl.egg-info/PKG-INFO b/gafl/gafl.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..4369d07aa8261a6ceeea5612be66717100da26f5 --- /dev/null +++ b/gafl/gafl.egg-info/PKG-INFO @@ -0,0 +1,7 @@ +Metadata-Version: 2.4 +Name: gafl +Version: 0.0.0 +License-File: LICENSE +License-File: NOTICE.md +License-File: AUTHORS.md +Dynamic: license-file diff --git a/gafl/gafl.egg-info/SOURCES.txt b/gafl/gafl.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..5fa7a5eb49499c832d3815cd988179f123889574 --- /dev/null +++ b/gafl/gafl.egg-info/SOURCES.txt @@ -0,0 +1,11 @@ +AUTHORS.md +LICENSE +NOTICE.md +README.md +setup.py +gafl/experiment_utils.py +gafl.egg-info/PKG-INFO +gafl.egg-info/SOURCES.txt +gafl.egg-info/dependency_links.txt +gafl.egg-info/top_level.txt +openfold/config.py \ No newline at end of file diff --git a/gafl/gafl.egg-info/dependency_links.txt b/gafl/gafl.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/gafl/gafl.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/gafl/gafl.egg-info/top_level.txt b/gafl/gafl.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..020c04c941ea30b294af4d7e3c871700a1ae67cf --- /dev/null +++ b/gafl/gafl.egg-info/top_level.txt @@ -0,0 +1,2 @@ +gafl +openfold diff --git a/gafl/gafl/__pycache__/experiment_utils.cpython-310.pyc b/gafl/gafl/__pycache__/experiment_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20c7f4a8a2ee0176d1df345203902dca0f4c9587 Binary files /dev/null and b/gafl/gafl/__pycache__/experiment_utils.cpython-310.pyc differ diff --git a/gafl/gafl/__pycache__/experiment_utils.cpython-311.pyc b/gafl/gafl/__pycache__/experiment_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2793716526b8ebcf6be6e82d45b7f0587b109fc1 Binary files /dev/null and b/gafl/gafl/__pycache__/experiment_utils.cpython-311.pyc differ diff --git a/gafl/gafl/analysis/__init__.py b/gafl/gafl/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/gafl/analysis/__pycache__/__init__.cpython-310.pyc b/gafl/gafl/analysis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3183b8ebdc219ed3c0461f368c9cedd8f76561cd Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/__init__.cpython-310.pyc differ diff --git a/gafl/gafl/analysis/__pycache__/__init__.cpython-311.pyc b/gafl/gafl/analysis/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d75eddd3bbab496861d87b1b3de3e6dd35303e86 Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/__init__.cpython-311.pyc differ diff --git a/gafl/gafl/analysis/__pycache__/metrics.cpython-310.pyc b/gafl/gafl/analysis/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9def1cc75b777fc69b41c961f2dcd536ce9ce505 Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/metrics.cpython-310.pyc differ diff --git a/gafl/gafl/analysis/__pycache__/metrics.cpython-311.pyc b/gafl/gafl/analysis/__pycache__/metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe9c0c8f92cca87586aad524d922ff3321784820 Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/metrics.cpython-311.pyc differ diff --git a/gafl/gafl/analysis/__pycache__/utils.cpython-310.pyc b/gafl/gafl/analysis/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73f528124b8d5ef20b0331869feadee146b92dbe Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/utils.cpython-310.pyc differ diff --git a/gafl/gafl/analysis/__pycache__/utils.cpython-311.pyc b/gafl/gafl/analysis/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2ee62c8501f03e06692d74837fa61e84f6e64a8 Binary files /dev/null and b/gafl/gafl/analysis/__pycache__/utils.cpython-311.pyc differ diff --git a/gafl/gafl/analysis/metrics.py b/gafl/gafl/analysis/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..03543c60cde3baf5da0e6a017bc4c63a1dc060b0 --- /dev/null +++ b/gafl/gafl/analysis/metrics.py @@ -0,0 +1,59 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" Metrics. """ +import mdtraj as md +import numpy as np +from openfold.np import residue_constants +from tmtools import tm_align +from gafl.data import utils as du + + +def calc_tm_score(pos_1, pos_2, seq_1, seq_2): + tm_results = tm_align(pos_1, pos_2, seq_1, seq_2) + return tm_results.tm_norm_chain1, tm_results.tm_norm_chain2 + +def calc_mdtraj_metrics(pdb_path): + try: + traj = md.load(pdb_path) + pdb_ss = md.compute_dssp(traj, simplified=True) + pdb_coil_percent = np.mean(pdb_ss == 'C') + pdb_helix_percent = np.mean(pdb_ss == 'H') + pdb_strand_percent = np.mean(pdb_ss == 'E') + pdb_ss_percent = pdb_helix_percent + pdb_strand_percent + pdb_rg = md.compute_rg(traj)[0] + except IndexError as e: + print('Error in calc_mdtraj_metrics: {}'.format(e)) + pdb_ss_percent = 0.0 + pdb_coil_percent = 0.0 + pdb_helix_percent = 0.0 + pdb_strand_percent = 0.0 + pdb_rg = 0.0 + return { + 'non_coil_percent': pdb_ss_percent, + 'coil_percent': pdb_coil_percent, + 'helix_percent': pdb_helix_percent, + 'strand_percent': pdb_strand_percent, + 'radius_of_gyration': pdb_rg, + } + +def calc_ca_ca_metrics(ca_pos, bond_tol=0.1, clash_tol=1.0): + ca_bond_dists = np.linalg.norm( + ca_pos - np.roll(ca_pos, 1, axis=0), axis=-1)[1:] + ca_ca_dev = np.mean(np.abs(ca_bond_dists - residue_constants.ca_ca)) + ca_ca_valid = np.mean(ca_bond_dists < (residue_constants.ca_ca + bond_tol)) + + ca_ca_dists2d = np.linalg.norm( + ca_pos[:, None, :] - ca_pos[None, :, :], axis=-1) + inter_dists = ca_ca_dists2d[np.where(np.triu(ca_ca_dists2d, k=0) > 0)] + clashes = inter_dists < clash_tol + return { + 'ca_ca_deviation': ca_ca_dev, + 'ca_ca_valid_percent': ca_ca_valid, + 'num_ca_ca_clashes': np.sum(clashes), + } + +def calc_aligned_rmsd(pos_1, pos_2): + aligned_pos_1 = du.rigid_transform_3D(pos_1, pos_2)[0] + return np.mean(np.linalg.norm(aligned_pos_1 - pos_2, axis=-1)) \ No newline at end of file diff --git a/gafl/gafl/analysis/sc_dataset.py b/gafl/gafl/analysis/sc_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..cb834ce028c83892549d2cd30831197526abd0d9 --- /dev/null +++ b/gafl/gafl/analysis/sc_dataset.py @@ -0,0 +1,223 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import os +import numpy as np +import torch +import subprocess +from typing import Optional +from biotite.sequence.io import fasta +import pandas as pd +# import esm +# from esm.esmfold.v1.esmfold import ESMFold +from tqdm import tqdm +import esm +import pickle +from analysis import utils as au +from gafl.data import utils as du +from gafl.analysis import metrics + +def filter_trainset(path: str): + for file in tqdm(os.listdir(path)): + if file.endswith(".pkl"): + with open(os.path.join(path, file), 'rb') as f: + structure = pickle.load(f) + + #Get number of unique residues + length = len(structure['residue_index']) + + if length > 128: + continue + + atom_pos = structure['atom_positions'] + os.makedirs(os.path.join(path, 'self_consistency', file.replace('.pkl', '')), exist_ok=True) + au.write_prot_to_pdb(atom_pos, os.path.join(path, 'self_consistency', file.replace('.pkl', ''), "sample.pdb"), overwrite=True, no_indexing=True) + +def run_self_consistency_batch( + path: str, + pdb_count = None, + max_esm_batch = 10, + length_interval = None, + motif_mask: Optional[np.ndarray]=None, + calc_non_coil_rmsd: bool = False + ): + """ + """ + + sequences_per_sample = 8 + folding_model = esm.pretrained.esmfold_v1().eval() + folding_model = folding_model.cuda() + + # os.makedirs(os.path.join(path, "self_consistency"), exist_ok=True) + + with torch.no_grad(): + fasta_headers = [] + fasta_seqs = [] + processed_pdbs = [] + print("Running ProteinMPNN on filtered training samples...") + # for sample_id in tqdm(sample_ids, desc="ProteinMPNN for samples"): + + files = os.listdir(path) + if pdb_count is not None: + files = files[:pdb_count] + + for file in tqdm(files): + if not os.path.isdir(os.path.join(path, file)): + continue + if length_interval is not None: + pdb_length = au.get_pdb_length(os.path.join(path, file, "sample.pdb")) + if pdb_length < length_interval[0] or pdb_length > length_interval[1]: + continue + + processed_pdbs.append(file) + decoy_pdb_dir = os.path.join(path, file) + reference_pdb_path = os.path.join(decoy_pdb_dir, 'sample.pdb') + + # Run PorteinMPNN + output_path = os.path.join(decoy_pdb_dir, "parsed_pdbs.jsonl") + # print(output_path) + process = subprocess.Popen([ + 'python', + f'./ProteinMPNN/helper_scripts/parse_multiple_chains.py', + f'--input_path={decoy_pdb_dir}', + f'--output_path={output_path}', + ]) + # print(process) + _ = process.wait() + num_tries = 0 + ret = -1 + pmpnn_args = [ + 'python', + f'./ProteinMPNN/protein_mpnn_run.py', + '--out_folder', + decoy_pdb_dir, + '--jsonl_path', + output_path, + '--num_seq_per_target', + str(sequences_per_sample), + '--sampling_temp', + '0.1', + '--seed', + '38', + '--batch_size', + '1', + '--device', + '0' + ] + # print(pmpnn_args) + while ret < 0: + try: + process = subprocess.Popen( + pmpnn_args, + stdout=subprocess.DEVNULL, + stderr=subprocess.STDOUT + ) + ret = process.wait() + except Exception as e: + num_tries += 1 + print(f'Failed ProteinMPNN. Attempt {num_tries}/5') + torch.cuda.empty_cache() + if num_tries > 4: + raise e + mpnn_fasta_path = os.path.join( + decoy_pdb_dir, + 'seqs', + os.path.basename(reference_pdb_path).replace('.pdb', '.fa') + ) + # print(mpnn_fasta_path) + + fasta_file = fasta.FastaFile.read(mpnn_fasta_path) + fasta_headers.extend(list(fasta_file.keys())[1:]) + fasta_seqs.extend(list(fasta_file.values())[1:]) + + slice_size = sequences_per_sample * max_esm_batch + slices = [(i,i+slice_size) for i in range(0, len(fasta_seqs), slice_size)] + + print(f"Run ESM on predicted sequences") + for j, s in tqdm(enumerate(slices), total=len(slices)): + # Run ESMFold on each ProteinMPNN sequence + all_esm_output = folding_model.infer(fasta_seqs[s[0]:s[1]]) + all_esm_pdbs = folding_model.output_to_pdb(all_esm_output) + # print(all_esm_output.keys()) + + # Run ESMFold on each ProteinMPNN sequence and calculate metrics. + mpnn_results = { + 'tm_score': [], + 'sample_path': [], + 'header': [], + 'sequence': [], + 'rmsd': [], + } + if calc_non_coil_rmsd: + mpnn_results['non_coil_rmsd'] = [] + if motif_mask is not None: + # Only calculate motif RMSD if mask is specified. + mpnn_results['motif_rmsd'] = [] + # for i in tqdm(range(len(fasta_seqs)), desc="Calc metrics and save"): + for i in range(len(fasta_seqs[s[0]:s[1]])): + header = fasta_headers[s[0]:s[1]][i] + sequence = fasta_seqs[s[0]:s[1]][i] + # esm_output = all_esm_output[i] + esm_pdb = all_esm_pdbs[i] + decoy_pdb_dir = os.path.join(path, processed_pdbs[i//sequences_per_sample + j*max_esm_batch]) + reference_pdb_path = os.path.join(decoy_pdb_dir, 'sample.pdb') + + esmf_dir = os.path.join(decoy_pdb_dir, 'esmf') + os.makedirs(esmf_dir, exist_ok=True) + + esmf_sample_path = os.path.join(esmf_dir, f'sample_{i%sequences_per_sample}.pdb') + with open(esmf_sample_path, "w") as f: + f.write(esm_pdb) + + sample_feats = du.parse_pdb_feats('sample', reference_pdb_path) + esmf_feats = du.parse_pdb_feats('folded_sample', esmf_sample_path, calc_dssp=calc_non_coil_rmsd) + sample_seq = du.aatype_to_seq(sample_feats['aatype']) + + # Calculate scTM of ESMFold outputs with reference protein + _, tm_score = metrics.calc_tm_score( + sample_feats['bb_positions'], esmf_feats['bb_positions'], + sample_seq, sample_seq) + rmsd = metrics.calc_aligned_rmsd( + sample_feats['bb_positions'], esmf_feats['bb_positions']) + + if calc_non_coil_rmsd: + # calculate the rmsd if coils in the refolded structure are ignored: + non_coil_idxs = np.where(esmf_feats['dssp'] != 'C')[0] + if len(non_coil_idxs) == 0: + non_coil_rmsd = np.nan + else: + non_coil_rmsd = metrics.calc_aligned_rmsd( + sample_feats['bb_positions'][non_coil_idxs], + esmf_feats['bb_positions'][non_coil_idxs]) + + if motif_mask is not None: + sample_motif = sample_feats['bb_positions'][motif_mask] + of_motif = esmf_feats['bb_positions'][motif_mask] + motif_rmsd = metrics.calc_aligned_rmsd( + sample_motif, of_motif) + mpnn_results['motif_rmsd'].append(motif_rmsd) + mpnn_results['rmsd'].append(rmsd) + if calc_non_coil_rmsd: + mpnn_results['non_coil_rmsd'].append(non_coil_rmsd) + mpnn_results['tm_score'].append(tm_score) + mpnn_results['sample_path'].append(esmf_sample_path) + mpnn_results['header'].append(header) + mpnn_results['sequence'].append(sequence) + + + if (i+1) % sequences_per_sample == 0: + if i > 0: + # Save results to CSV + csv_path = os.path.join(decoy_pdb_dir, 'sc_results.csv') + mpnn_results = pd.DataFrame(mpnn_results) + mpnn_results.to_csv(csv_path) + mpnn_results = { + 'tm_score': [], + 'sample_path': [], + 'header': [], + 'sequence': [], + 'rmsd': [], + } + if calc_non_coil_rmsd: + mpnn_results['non_coil_rmsd'] = [] \ No newline at end of file diff --git a/gafl/gafl/analysis/utils.py b/gafl/gafl/analysis/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe12a01686d9d558c12a98dcb0135ccbb2c097db --- /dev/null +++ b/gafl/gafl/analysis/utils.py @@ -0,0 +1,102 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import numpy as np +import os +import re +from openfold.utils import rigid_utils +from Bio import PDB +from gafl.data import protein +from pathlib import Path + + +Rigid = rigid_utils.Rigid + + +def create_full_prot( + atom37: np.ndarray, + atom37_mask: np.ndarray, + aatype=None, + b_factors=None, + ): + assert atom37.ndim == 3 + assert atom37.shape[-1] == 3 + assert atom37.shape[-2] == 37 + n = atom37.shape[0] + residue_index = np.arange(n) + chain_index = np.zeros(n) + if b_factors is None: + b_factors = np.zeros([n, 37]) + if aatype is None: + aatype = np.zeros(n, dtype=int) + return protein.Protein( + atom_positions=atom37, + atom_mask=atom37_mask, + aatype=aatype, + residue_index=residue_index, + chain_index=chain_index, + b_factors=b_factors) + + +def write_prot_to_pdb( + prot_pos: np.ndarray, + file_path: str, + aatype: np.ndarray=None, + overwrite=False, + no_indexing=False, + b_factors=None, + ): + if overwrite: + max_existing_idx = 0 + else: + file_dir = os.path.dirname(file_path) + file_name = os.path.basename(file_path).strip('.pdb') + existing_files = [x for x in os.listdir(str(Path(file_dir).absolute())) if file_name in x] + max_existing_idx = max([ + int(re.findall(r'_(\d+).pdb', x)[0]) for x in existing_files if re.findall(r'_(\d+).pdb', x) + if re.findall(r'_(\d+).pdb', x)] + [0]) + if not no_indexing: + save_path = file_path.replace('.pdb', '') + f'_{max_existing_idx+1}.pdb' + else: + save_path = file_path + with open(save_path, 'w') as f: + if prot_pos.ndim == 4: + for t, pos37 in enumerate(prot_pos): + atom37_mask = np.sum(np.abs(pos37), axis=-1) > 1e-7 + prot = create_full_prot( + pos37, atom37_mask, aatype=aatype, b_factors=b_factors) + pdb_prot = protein.to_pdb(prot, model=t + 1, add_end=False) + f.write(pdb_prot) + elif prot_pos.ndim == 3: + atom37_mask = np.sum(np.abs(prot_pos), axis=-1) > 1e-7 + prot = create_full_prot( + prot_pos, atom37_mask, aatype=aatype, b_factors=b_factors) + pdb_prot = protein.to_pdb(prot, model=1, add_end=False) + f.write(pdb_prot) + else: + raise ValueError(f'Invalid positions shape {prot_pos.shape}') + f.write('END') + return save_path + +def get_pdb_length(path: str): + # Initialize the PDB parser + parser = PDB.PDBParser(QUIET=True) # QUIET=True suppresses some warnings + + # Parse the PDB file + structure = parser.get_structure("sample", path) + + # Initialize a set to track unique residues + unique_residues = set() + + # Iterate through the chains and residues in the structure + for model in structure: + for chain in model: + for residue in chain: + # Residue's ID is a tuple (hetero-flag, sequence number, insertion code) + # Only consider non-hetero residues (ignore water, ions, etc.) + if residue.id[0] == " ": + unique_residues.add(residue.id) + + # Get the total number of unique residues + return len(unique_residues) \ No newline at end of file diff --git a/gafl/gafl/data/__pycache__/all_atom.cpython-310.pyc b/gafl/gafl/data/__pycache__/all_atom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33d2a204aaee5b0740ec7c3d56cf9eb27b076404 Binary files /dev/null and b/gafl/gafl/data/__pycache__/all_atom.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/all_atom.cpython-311.pyc b/gafl/gafl/data/__pycache__/all_atom.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c68989bf39a6cf1078f80710ae54c337a6873b04 Binary files /dev/null and b/gafl/gafl/data/__pycache__/all_atom.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/interpolant.cpython-310.pyc b/gafl/gafl/data/__pycache__/interpolant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b5384b6fc9c20b696021dbf1aa0eee691293455 Binary files /dev/null and b/gafl/gafl/data/__pycache__/interpolant.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/interpolant.cpython-311.pyc b/gafl/gafl/data/__pycache__/interpolant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6932159198feda767dda8b1db1cdcc3ceaea0ea5 Binary files /dev/null and b/gafl/gafl/data/__pycache__/interpolant.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/protein.cpython-310.pyc b/gafl/gafl/data/__pycache__/protein.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6beed12c8707ab40119a8a58fe1b9ffdf899e06 Binary files /dev/null and b/gafl/gafl/data/__pycache__/protein.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/protein.cpython-311.pyc b/gafl/gafl/data/__pycache__/protein.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44bf152482dda62a388d5ea52451fc791af9d378 Binary files /dev/null and b/gafl/gafl/data/__pycache__/protein.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/quarternion_utils.cpython-310.pyc b/gafl/gafl/data/__pycache__/quarternion_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1a1ba687ff73a406f4b4928ad602920c0a81dd Binary files /dev/null and b/gafl/gafl/data/__pycache__/quarternion_utils.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/quarternion_utils.cpython-311.pyc b/gafl/gafl/data/__pycache__/quarternion_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4b86839d907a7eb47d6997281dbc9c49facc41e Binary files /dev/null and b/gafl/gafl/data/__pycache__/quarternion_utils.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/residue_constants.cpython-310.pyc b/gafl/gafl/data/__pycache__/residue_constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..640ab770d5e6f2c2a492e4f3f3ba383950cdb166 Binary files /dev/null and b/gafl/gafl/data/__pycache__/residue_constants.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/residue_constants.cpython-311.pyc b/gafl/gafl/data/__pycache__/residue_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e022bdab43abe095d77dcf8227dd7b17da4b87c4 Binary files /dev/null and b/gafl/gafl/data/__pycache__/residue_constants.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/so3_utils.cpython-310.pyc b/gafl/gafl/data/__pycache__/so3_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cf0b737e8c8ba11aaa443671f595912f8f7f56a Binary files /dev/null and b/gafl/gafl/data/__pycache__/so3_utils.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/so3_utils.cpython-311.pyc b/gafl/gafl/data/__pycache__/so3_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d64278f836c29773bdc72dfb37342c84025a5829 Binary files /dev/null and b/gafl/gafl/data/__pycache__/so3_utils.cpython-311.pyc differ diff --git a/gafl/gafl/data/__pycache__/utils.cpython-310.pyc b/gafl/gafl/data/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a122d1c5e77161b30adb93b0695b4637895349 Binary files /dev/null and b/gafl/gafl/data/__pycache__/utils.cpython-310.pyc differ diff --git a/gafl/gafl/data/__pycache__/utils.cpython-311.pyc b/gafl/gafl/data/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f099ec80c0f7dab53abd6ab7be37a22f68ae9ff Binary files /dev/null and b/gafl/gafl/data/__pycache__/utils.cpython-311.pyc differ diff --git a/gafl/gafl/data/all_atom.py b/gafl/gafl/data/all_atom.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe24aa7ba317d60e6a3c1fb276c6b077bfe5116 --- /dev/null +++ b/gafl/gafl/data/all_atom.py @@ -0,0 +1,296 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utilities for calculating all atom representations. +Code adapted from OpenFold. +""" + +import torch +from openfold.data import data_transforms +from openfold.np import residue_constants +from openfold.utils import rigid_utils as ru + +from gafl.data import utils as du + +Rigid = ru.Rigid +Rotation = ru.Rotation + +# Residue Constants from OpenFold/AlphaFold2. + + +IDEALIZED_POS = torch.tensor(residue_constants.restype_atom14_rigid_group_positions) +DEFAULT_FRAMES = torch.tensor(residue_constants.restype_rigid_group_default_frame) +ATOM_MASK = torch.tensor(residue_constants.restype_atom14_mask) +GROUP_IDX = torch.tensor(residue_constants.restype_atom14_to_rigid_group) + + +def to_atom37(trans, rots): + num_batch, num_res, _ = trans.shape + final_atom37 = compute_backbone( + du.create_rigid(rots, trans), + torch.zeros(num_batch, num_res, 2, device=trans.device) + )[0] + return final_atom37 + + +def torsion_angles_to_frames( + r: Rigid, # type: ignore [valid-type] + alpha: torch.Tensor, + aatype: torch.Tensor, +): + """Conversion method of torsion angles to frames provided the backbone. + + Args: + r: Backbone rigid groups. + alpha: Torsion angles. + aatype: residue types. + + Returns: + All 8 frames corresponding to each torsion frame. + + """ + # [*, N, 8, 4, 4] + with torch.no_grad(): + default_4x4 = DEFAULT_FRAMES.to(aatype.device)[aatype, ...] # type: ignore [attr-defined] + + # [*, N, 8] transformations, i.e. + # One [*, N, 8, 3, 3] rotation matrix and + # One [*, N, 8, 3] translation matrix + default_r = r.from_tensor_4x4(default_4x4) # type: ignore [attr-defined] + + bb_rot = alpha.new_zeros((*((1,) * len(alpha.shape[:-1])), 2)) + bb_rot[..., 1] = 1 + + # [*, N, 8, 2] + alpha = torch.cat([bb_rot.expand(*alpha.shape[:-2], -1, -1), alpha], dim=-2) + + # [*, N, 8, 3, 3] + # Produces rotation matrices of the form: + # [ + # [1, 0 , 0 ], + # [0, a_2,-a_1], + # [0, a_1, a_2] + # ] + # This follows the original code rather than the supplement, which uses + # different indices. + + all_rots = alpha.new_zeros(default_r.get_rots().get_rot_mats().shape) + all_rots[..., 0, 0] = 1 + all_rots[..., 1, 1] = alpha[..., 1] + all_rots[..., 1, 2] = -alpha[..., 0] + all_rots[..., 2, 1:] = alpha + + all_rots = Rigid(Rotation(rot_mats=all_rots), None) + + all_frames = default_r.compose(all_rots) + + chi2_frame_to_frame = all_frames[..., 5] + chi3_frame_to_frame = all_frames[..., 6] + chi4_frame_to_frame = all_frames[..., 7] + + chi1_frame_to_bb = all_frames[..., 4] + chi2_frame_to_bb = chi1_frame_to_bb.compose(chi2_frame_to_frame) + chi3_frame_to_bb = chi2_frame_to_bb.compose(chi3_frame_to_frame) + chi4_frame_to_bb = chi3_frame_to_bb.compose(chi4_frame_to_frame) + + all_frames_to_bb = Rigid.cat( + [ + all_frames[..., :5], + chi2_frame_to_bb.unsqueeze(-1), + chi3_frame_to_bb.unsqueeze(-1), + chi4_frame_to_bb.unsqueeze(-1), + ], + dim=-1, + ) + + all_frames_to_global = r[..., None].compose(all_frames_to_bb) # type: ignore [index] + + return all_frames_to_global + + +def prot_to_torsion_angles(aatype, atom37, atom37_mask): + """Calculate torsion angle features from protein features.""" + prot_feats = { + "aatype": aatype, + "all_atom_positions": atom37, + "all_atom_mask": atom37_mask, + } + torsion_angles_feats = data_transforms.atom37_to_torsion_angles()(prot_feats) + torsion_angles = torsion_angles_feats["torsion_angles_sin_cos"] + torsion_mask = torsion_angles_feats["torsion_angles_mask"] + return torsion_angles, torsion_mask + + +def frames_to_atom14_pos( + r: Rigid, # type: ignore [valid-type] + aatype: torch.Tensor, +): + """Convert frames to their idealized all atom representation. + + Args: + r: All rigid groups. [..., N, 8, 3] + aatype: Residue types. [..., N] + + Returns: + + """ + with torch.no_grad(): + group_mask = GROUP_IDX.to(aatype.device)[aatype, ...] + group_mask = torch.nn.functional.one_hot( + group_mask, + num_classes=DEFAULT_FRAMES.shape[-3], + ) + frame_atom_mask = ATOM_MASK.to(aatype.device)[aatype, ...].unsqueeze(-1) # type: ignore [attr-defined] + frame_null_pos = IDEALIZED_POS.to(aatype.device)[aatype, ...] # type: ignore [attr-defined] + + # [*, N, 14, 8] + t_atoms_to_global = r[..., None, :] * group_mask # type: ignore [index] + + # [*, N, 14] + t_atoms_to_global = t_atoms_to_global.map_tensor_fn(lambda x: torch.sum(x, dim=-1)) + + # [*, N, 14, 3] + pred_positions = t_atoms_to_global.apply(frame_null_pos) + pred_positions = pred_positions * frame_atom_mask + + return pred_positions + + +def compute_backbone(bb_rigids, psi_torsions): + torsion_angles = torch.tile( + psi_torsions[..., None, :], tuple([1 for _ in range(len(bb_rigids.shape))]) + (7, 1) + ) + aatype = torch.zeros(bb_rigids.shape, device=bb_rigids.device).long() + # aatype = torch.zeros(bb_rigids.shape).long().to(bb_rigids.device) + all_frames = torsion_angles_to_frames( + bb_rigids, + torsion_angles, + aatype, + ) + atom14_pos = frames_to_atom14_pos(all_frames, aatype) + atom37_bb_pos = torch.zeros(bb_rigids.shape + (37, 3), device=bb_rigids.device) + # atom14 bb order = ['N', 'CA', 'C', 'O', 'CB'] + # atom37 bb order = ['N', 'CA', 'C', 'CB', 'O'] + atom37_bb_pos[..., :3, :] = atom14_pos[..., :3, :] + atom37_bb_pos[..., 3, :] = atom14_pos[..., 4, :] + atom37_bb_pos[..., 4, :] = atom14_pos[..., 3, :] + atom37_mask = torch.any(atom37_bb_pos, axis=-1) + return atom37_bb_pos, atom37_mask, aatype, atom14_pos + + +def calculate_neighbor_angles(R_ac, R_ab): + """Calculate angles between atoms c <- a -> b. + + Parameters + ---------- + R_ac: Tensor, shape = (N,3) + Vector from atom a to c. + R_ab: Tensor, shape = (N,3) + Vector from atom a to b. + + Returns + ------- + angle_cab: Tensor, shape = (N,) + Angle between atoms c <- a -> b. + """ + # cos(alpha) = (u * v) / (|u|*|v|) + x = torch.sum(R_ac * R_ab, dim=1) # shape = (N,) + # sin(alpha) = |u x v| / (|u|*|v|) + y = torch.cross(R_ac, R_ab).norm(dim=-1) # shape = (N,) + # avoid that for y == (0,0,0) the gradient wrt. y becomes NaN + y = torch.max(y, torch.tensor(1e-9)) + angle = torch.atan2(y, x) + return angle + + +def vector_projection(R_ab, P_n): + """ + Project the vector R_ab onto a plane with normal vector P_n. + + Parameters + ---------- + R_ab: Tensor, shape = (N,3) + Vector from atom a to b. + P_n: Tensor, shape = (N,3) + Normal vector of a plane onto which to project R_ab. + + Returns + ------- + R_ab_proj: Tensor, shape = (N,3) + Projected vector (orthogonal to P_n). + """ + a_x_b = torch.sum(R_ab * P_n, dim=-1) + b_x_b = torch.sum(P_n * P_n, dim=-1) + return R_ab - (a_x_b / b_x_b)[:, None] * P_n + + +def transrot_to_atom37(transrot_traj, res_mask=None): + if res_mask is None: + trans_zeroth_entry = transrot_traj[0][0] + res_mask = torch.ones_like(trans_zeroth_entry[...,0]).bool() + atom37_traj = [] + res_mask = res_mask.detach().cpu() + num_batch = res_mask.shape[0] + for trans, rots in transrot_traj: + rigids = du.create_rigid(rots, trans) + atom37 = compute_backbone( + rigids, + torch.zeros( + trans.shape[0], + trans.shape[1], + 2, + device=trans.device + ) + )[0] + atom37 = atom37.detach().cpu() + batch_atom37 = [] + for i in range(num_batch): + batch_atom37.append( + du.adjust_oxygen_pos(atom37[i], res_mask[i]) + ) + atom37_traj.append(torch.stack(batch_atom37)) + return atom37_traj + + +def atom37_from_trans_rot(trans, rots, res_mask): + rigids = du.create_rigid(rots, trans) + atom37 = compute_backbone( + rigids, + torch.zeros( + trans.shape[0], + trans.shape[1], + 2, + device=trans.device + ) + )[0] + atom37 = atom37.detach().cpu() + batch_atom37 = [] + num_batch = res_mask.shape[0] + for i in range(num_batch): + batch_atom37.append( + du.adjust_oxygen_pos(atom37[i], res_mask[i]) + ) + return torch.stack(batch_atom37) + + +def process_trans_rot_traj(trans_traj, rots_traj, res_mask): + res_mask = res_mask.detach().cpu() + atom37_traj = [ + atom37_from_trans_rot(trans, rots, res_mask) + for trans, rots in zip(trans_traj, rots_traj) + ] + atom37_traj = torch.stack(atom37_traj).swapaxes(0, 1) + return atom37_traj diff --git a/gafl/gafl/data/errors.py b/gafl/gafl/data/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..70479e1f11607d0f30b85e169eb96c540b32b763 --- /dev/null +++ b/gafl/gafl/data/errors.py @@ -0,0 +1,30 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Error class for handled errors.""" + + +class DataError(Exception): + """Data exception.""" + pass + + +class FileExistsError(DataError): + """Raised when file already exists.""" + pass + + +class MmcifParsingError(DataError): + """Raised when mmcif parsing fails.""" + pass + + +class ResolutionError(DataError): + """Raised when resolution isn't acceptable.""" + pass + + +class LengthError(DataError): + """Raised when length isn't acceptable.""" + pass \ No newline at end of file diff --git a/gafl/gafl/data/interpolant.py b/gafl/gafl/data/interpolant.py new file mode 100644 index 0000000000000000000000000000000000000000..438e50098b6b035abad431d3b2c007666cbd26e7 --- /dev/null +++ b/gafl/gafl/data/interpolant.py @@ -0,0 +1,414 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import torch +from typing import Tuple +from scipy.spatial.transform import Rotation +from scipy.optimize import linear_sum_assignment +import copy +import logging + +from gafl.data import so3_utils +from gafl.data import utils as du +from gafl.data import all_atom + + +def _centered_gaussian(num_batch, num_res, device): + noise = torch.randn(num_batch, num_res, 3, device=device) + return noise - torch.mean(noise, dim=-2, keepdims=True) + +def _uniform_so3(num_batch, num_res, device): + return torch.tensor( + Rotation.random(num_batch*num_res).as_matrix(), + device=device, + dtype=torch.float32, + ).reshape(num_batch, num_res, 3, 3) + +def _trans_diffuse_mask(trans_t, trans_1, diffuse_mask): + return trans_t * diffuse_mask[..., None] + trans_1 * (1 - diffuse_mask[..., None]) + +def _rots_diffuse_mask(rotmats_t, rotmats_1, diffuse_mask): + return ( + rotmats_t * diffuse_mask[..., None, None] + + rotmats_1 * (1 - diffuse_mask[..., None, None]) + ) + + +class Interpolant: + + def __init__(self, cfg): + self._cfg = cfg + self._rots_cfg = cfg.rots + self._trans_cfg = cfg.trans + self._sample_cfg = cfg.sampling + self._igso3 = None + self._log = logging.getLogger(__name__) + + BACKWARDS_COMPATIBLITITY = True + + if BACKWARDS_COMPATIBLITITY: # apply old config settings if new keys are not present + if hasattr(self._cfg, 'noise_res_scaling_power'): + self.noise_res_scaling_power = self._cfg.noise_res_scaling_power + else: + self.noise_res_scaling_power = 0 + + if hasattr(self._cfg, 'noise_scale'): + self.noise_scale = self._cfg.noise_scale + else: + self.noise_scale = 1.0 + + if hasattr(self._cfg, 'after_ot_noise'): + self.after_ot_noise = self._cfg.after_ot_noise + else: + self.after_ot_noise = False + + if hasattr(self._cfg, 'instance_ot'): + self.instance_ot = self._cfg.instance_ot + else: + self.instance_ot = False + + if hasattr(self._cfg, 'igso3_training'): + self.igso3_training = self._cfg.igso3_training + elif self.instance_ot: + self.igso3_training = False + else: + self.igso3_training = True + + if hasattr(self._cfg, 't_interval'): + self.t_interval = self._cfg.t_interval + else: + self.t_interval = [0, 1] + + if hasattr(self._cfg, 't_sampling_focus'): + self.t_sampling_focus = self._cfg.t_sampling_focus + else: + self.t_sampling_focus = 0. + + else: + self.noise_res_scaling_power = self._cfg.noise_res_scaling_power + self.noise_scale = self._cfg.noise_scale + self.after_ot_noise = self._cfg.after_ot_noise + self.instance_ot = self._cfg.instance_ot + + if self.instance_ot: + raise NotImplementedError("Instance OT is not implemented") + + @property + def igso3(self): + if self._igso3 is None: + sigma_grid = torch.linspace(0.1, 1.5, 1000) + self._igso3 = so3_utils.SampleIGSO3( + 1000, sigma_grid, cache_dir='.cache') + return self._igso3 + + def set_device(self, device): + self._device = device + if self.instance_ot: + self.permuter.to(self._device) + + def sample_t(self, num_batch): + t = torch.rand(num_batch, device=self._device) + + # transform the uniform distribution to the mode distribution + s = self.t_sampling_focus + if s != 0: + t = self.f_mode_transformation(t, s) + + # Map to training interval + t = self.t_interval[0] + t * (self.t_interval[1] - self.t_interval[0]) + + return t * (1 - 2*self._cfg.min_t) + self._cfg.min_t + + @staticmethod + def f_mode_transformation(t, s): + """ + Transformation to the mode distribution from https://arxiv.org/abs/2403.03206 + """ + # Ensure s is a float, and t is a torch.Tensor + s = float(s) + u = 1 - t - s * (torch.cos(torch.pi / 2 * t) ** 2 - 1 + t) + return u + + def _corrupt_trans(self, noisy_batch): + trans_nm_0 = _centered_gaussian(*noisy_batch['res_mask'].shape, self._device) + trans_0 = trans_nm_0 * du.NM_TO_ANG_SCALE + trans_0 *= self.noise_scale + + # make the noise blob larger the longer the protein is: + if self.noise_res_scaling_power > 0: + trans_0 *= (trans_0.shape[1] / 128.)**self.noise_res_scaling_power + + trans_0 = self._batch_ot(trans_0, noisy_batch['trans_1'], noisy_batch['res_mask']) + + #NOTE: this is not optimal yet: we do batch OT and kabsch alignment before intra-batch OT (this would be much more expensive otherwise!) + if self.instance_ot: + noisy_batch['trans_0'] = trans_0 + # reorders trans_0 according to the optimal permutation + noisy_batch = _ot_permutation(noisy_batch=noisy_batch) + + # kabsch align again (lazy: could be done better) + # (this also allows to interachange batches, which will probably not happen due to the node optimal transport. its just in here for simplicity, we actually only need the kabsch alignment) + trans_0 = self._batch_ot(noisy_batch['trans_0'], noisy_batch['trans_1'], noisy_batch['res_mask']) + + # add more noise to teach the model that it should move the residues more: + if self.after_ot_noise > 0: + trans_nm_0_add = _centered_gaussian(*noisy_batch['res_mask'].shape, self._device) + trans_0_add = trans_nm_0_add * du.NM_TO_ANG_SCALE + trans_0_add *= self.after_ot_noise + trans_0 += trans_0_add + + noisy_batch['trans_0'] = trans_0 + + t = noisy_batch['t'] + trans_1 = noisy_batch['trans_1'] + res_mask = noisy_batch['res_mask'] + + trans_t = (1 - t[..., None]) * trans_0 + t[..., None] * trans_1 + trans_t = _trans_diffuse_mask(trans_t, trans_1, res_mask) + trans_t = trans_t * res_mask[..., None] + + noisy_batch['trans_t'] = trans_t + + return noisy_batch + + def _batch_ot(self, trans_0, trans_1, res_mask): + num_batch, num_res = trans_0.shape[:2] + noise_idx, gt_idx = torch.where( + torch.ones(num_batch, num_batch)) + batch_nm_0 = trans_0[noise_idx] + batch_nm_1 = trans_1[gt_idx] + batch_mask = res_mask[gt_idx] + aligned_nm_0, aligned_nm_1, _ = du.batch_align_structures( + batch_nm_0, batch_nm_1, mask=batch_mask + ) + aligned_nm_0 = aligned_nm_0.reshape(num_batch, num_batch, num_res, 3) + aligned_nm_1 = aligned_nm_1.reshape(num_batch, num_batch, num_res, 3) + + # Compute cost matrix of aligned noise to ground truth + batch_mask = batch_mask.reshape(num_batch, num_batch, num_res) + cost_matrix = torch.sum( + torch.linalg.norm(aligned_nm_0 - aligned_nm_1, dim=-1), dim=-1 + ) / torch.sum(batch_mask, dim=-1) + noise_perm, gt_perm = linear_sum_assignment(du.to_numpy(cost_matrix)) + return aligned_nm_0[(tuple(gt_perm), tuple(noise_perm))] + + def _corrupt_rotmats(self, rotmats_1, t, res_mask): + num_batch, num_res = res_mask.shape + ############################ + # NOTE: use uniform noise instead of igso3 + # noisy_rotmats = self.igso3.sample( + # torch.tensor([1.5]), + # num_batch*num_res + # ).to(self._device) + if self.igso3_training: + noisy_rotmats = self.igso3.sample(torch.tensor([1.5]), num_batch*num_res).to(self._device) + noisy_rotmats = noisy_rotmats.reshape(num_batch, num_res, 3, 3) + rotmats_0 = torch.einsum( + "...ij,...jk->...ik", rotmats_1, noisy_rotmats) + else: + noisy_rotmats = _uniform_so3(num_batch, num_res, self._device) + ############################ + + rotmats_t = so3_utils.geodesic_t(t[..., None], rotmats_1, rotmats_0) + identity = torch.eye(3, device=self._device) + rotmats_t = ( + rotmats_t * res_mask[..., None, None] + + identity[None, None] * (1 - res_mask[..., None, None]) + ) + return _rots_diffuse_mask(rotmats_t, rotmats_1, res_mask) + + def corrupt_batch(self, batch, t=None): + noisy_batch = copy.deepcopy(batch) + num_batch, _ = batch['res_mask'].shape + + # [B, 1] + if t is None: + t = self.sample_t(num_batch)[:, None] + else: + t = torch.ones(num_batch, 1, device=self._device, dtype=torch.float32) * t + noisy_batch['t'] = t + + # Apply corruptions + noisy_batch = self._corrupt_trans(noisy_batch) + + # [B, N, 3] + trans_1 = batch['trans_1'] # Angstrom + + # [B, N, 3, 3] + rotmats_1 = batch['rotmats_1'] + + # [B, N] + res_mask = batch['res_mask'] + + rotmats_t = self._corrupt_rotmats(rotmats_1, t, res_mask) + noisy_batch['rotmats_t'] = rotmats_t + return noisy_batch + + def rot_sample_kappa(self, t): + if self._rots_cfg.sample_schedule == 'exp': + return 1 - torch.exp(-t*self._rots_cfg.exp_rate) + elif self._rots_cfg.sample_schedule == 'linear': + return t + else: + raise ValueError( + f'Invalid schedule: {self._rots_cfg.sample_schedule}') + + def _trans_euler_step(self, d_t, t, trans_1, trans_t): + trans_vf = (trans_1 - trans_t) / (1 - t) + return trans_t + trans_vf * d_t + + def _rots_euler_step(self, d_t, t, rotmats_1, rotmats_t): + if self._rots_cfg.sample_schedule == 'linear': + scaling = 1 / (1 - t) + elif self._rots_cfg.sample_schedule == 'exp': + scaling = self._rots_cfg.exp_rate + else: + raise ValueError( + f'Unknown sample schedule {self._rots_cfg.sample_schedule}') + return so3_utils.geodesic_t( + scaling * d_t, rotmats_1, rotmats_t) + + def sample( + self, + num_batch, + num_res, + model, + prior_sample:Tuple[torch.Tensor, torch.Tensor]=None, + save_path=None, + ): + res_mask = torch.ones(num_batch, num_res, device=self._device) + batch = { + 'res_mask': res_mask, + } + + if prior_sample is None: + # Set-up initial prior samples + ################## + trans_0 = _centered_gaussian( + num_batch, num_res, self._device) * du.NM_TO_ANG_SCALE + # make the noise blob larger the longer the protein is: + if self.noise_res_scaling_power > 0: + trans_0 *= (trans_0.shape[1] / 60.)**self.noise_res_scaling_power + + trans_0 *= self.noise_scale + ################## + + rotmats_0 = _uniform_so3(num_batch, num_res, self._device) + + if self.instance_ot: + batch['trans_t'] = trans_0 + batch['rotmats_t'] = rotmats_0 + + batch = self.permuter(batch) + + trans_0 = batch['trans_t'] + rotmats_0 = batch['rotmats_t'] + + + # add noise after the order prediction: + # only really makes sense with instance_ot + if self.after_ot_noise: + trans_nm_0_add = _centered_gaussian(num_batch, num_res, self._device) + trans_0_add = trans_nm_0_add * du.NM_TO_ANG_SCALE + trans_0_add *= self.noise_res_scaling_power + trans_0 += trans_0_add + + else: + raise NotImplementedError("This is not implemented yet") + trans_0, rotmats_0 = prior_sample + assert len(rotmats_0.shape) == 4, f"rotmats_0.shape: {rotmats_0.shape}" + assert len(trans_0.shape) == 3 + + if save_path is not None: + # save trans_0 and rotmats_0 + for i in range(num_batch): + torch.save(trans_0[i], save_path + f"/sample_{i}/trans_0.pt") + torch.save(rotmats_0[i], save_path + f"/sample_{i}/rotmats_0.pt") + + # Set-up time + ts = torch.linspace( + 0., 1.-self._cfg.min_t, self._sample_cfg.num_timesteps) + t_1 = ts[0] + + prot_traj = [(trans_0, rotmats_0)] + clean_traj = [] + for t_2 in ts[1:]: + + # Run model. + trans_t_1, rotmats_t_1 = prot_traj[-1] + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + t = torch.ones((num_batch, 1), device=self._device) * t_1 + batch['t'] = t + with torch.no_grad(): + model_out = model(batch) + + # Process model output. + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + if self._cfg.self_condition: + batch['trans_sc'] = pred_trans_1 + + # Take reverse step + d_t = t_2 - t_1 + trans_t_2 = self._trans_euler_step( + d_t, t_1, pred_trans_1, trans_t_1) + rotmats_t_2 = self._rots_euler_step( + d_t, t_1, pred_rotmats_1, rotmats_t_1) + prot_traj.append((trans_t_2, rotmats_t_2)) + t_1 = t_2 + + # We only integrated to min_t, so need to make a final step + t_1 = ts[-1] + trans_t_1, rotmats_t_1 = prot_traj[-1] + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + batch['t'] = torch.ones((num_batch, 1), device=self._device) * t_1 + with torch.no_grad(): + model_out = model(batch) + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + prot_traj.append((pred_trans_1, pred_rotmats_1)) + + # Convert trajectories to atom37. + atom37_traj = all_atom.transrot_to_atom37(prot_traj, res_mask) + clean_atom37_traj = all_atom.transrot_to_atom37(clean_traj, res_mask) + return atom37_traj, clean_atom37_traj, clean_traj + + +from sklearn.metrics import pairwise_distances +def _ot_permutation(noisy_batch)->torch.Tensor: + """ + Reorders the noisy trans_0 such that the translational distance between trans_0 and trans_1 is minimal. + Assumes shapes are [B, N, 3]. + """ + trans_0 = noisy_batch['trans_0'] + trans_1 = noisy_batch['trans_1'] + for b in range(trans_0.shape[0]): + cost_matrix = pairwise_distances(trans_1[b].numpy(force=True), trans_0[b].numpy(force=True)) + row_ind, col_ind = linear_sum_assignment(cost_matrix) + + + + # reorder trans_0 according to the optimal permutation: + + noisy_batch['trans_0'][b] = noisy_batch['trans_0'][b][col_ind] + + # do not permute res_mask, it should correspond to the target + # if 'res_mask' in noisy_batch: + # noisy_batch['res_mask'][b] = noisy_batch['res_mask'][b][col_ind] + # if 'res_idx' in noisy_batch: + # noisy_batch['res_idx'][b] = noisy_batch['res_idx'][b][col_ind] + # if 'aatype' in noisy_batch: + # noisy_batch['aatype'][b] = noisy_batch['aatype'][b][col_ind] + # if 'csv_idx' in noisy_batch: + # noisy_batch['csv_idx'][b] = noisy_batch['csv_idx'][b][col_ind] + + return noisy_batch \ No newline at end of file diff --git a/gafl/gafl/data/parsers.py b/gafl/gafl/data/parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..30517380097a455492d8db551d2869f411c1167f --- /dev/null +++ b/gafl/gafl/data/parsers.py @@ -0,0 +1,81 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Library for parsing different data structures. +Code adapted from Openfold protein.py. +""" +from Bio.PDB.Chain import Chain +import numpy as np + +from gafl.data import residue_constants +from gafl.data import protein + +Protein = protein.Protein + + +def process_chain(chain: Chain, chain_id: str) -> Protein: + """Convert a PDB chain object into a AlphaFold Protein instance. + + Forked from alphafold.common.protein.from_pdb_string + + WARNING: All non-standard residue types will be converted into UNK. All + non-standard atoms will be ignored. + + Took out lines 94-97 which don't allow insertions in the PDB. + Sabdab uses insertions for the chothia numbering so we need to allow them. + + Took out lines 110-112 since that would mess up CDR numbering. + + Args: + chain: Instance of Biopython's chain class. + + Returns: + Protein object with protein features. + """ + atom_positions = [] + aatype = [] + atom_mask = [] + residue_index = [] + b_factors = [] + chain_ids = [] + for res in chain: + res_shortname = residue_constants.restype_3to1.get(res.resname, 'X') + restype_idx = residue_constants.restype_order.get( + res_shortname, residue_constants.restype_num) + pos = np.zeros((residue_constants.atom_type_num, 3)) + mask = np.zeros((residue_constants.atom_type_num,)) + res_b_factors = np.zeros((residue_constants.atom_type_num,)) + for atom in res: + if atom.name not in residue_constants.atom_types: + continue + pos[residue_constants.atom_order[atom.name]] = atom.coord + mask[residue_constants.atom_order[atom.name]] = 1. + res_b_factors[residue_constants.atom_order[atom.name] + ] = atom.bfactor + aatype.append(restype_idx) + atom_positions.append(pos) + atom_mask.append(mask) + residue_index.append(res.id[1]) + b_factors.append(res_b_factors) + chain_ids.append(chain_id) + + return Protein( + atom_positions=np.array(atom_positions), + atom_mask=np.array(atom_mask), + aatype=np.array(aatype), + residue_index=np.array(residue_index), + chain_index=np.array(chain_ids), + b_factors=np.array(b_factors)) \ No newline at end of file diff --git a/gafl/gafl/data/pdb_dataloader.py b/gafl/gafl/data/pdb_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..2fadb39b4bd1c12f4bbc98b6bc205e0a4d9b34c5 --- /dev/null +++ b/gafl/gafl/data/pdb_dataloader.py @@ -0,0 +1,767 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""PDB data loader.""" +import math +import torch +import tree +import numpy as np +import torch +import pandas as pd +import ast +import logging +from tqdm import tqdm + +from openfold.data import data_transforms +from openfold.utils import rigid_utils + +from pytorch_lightning import LightningDataModule +from torch.utils.data import DataLoader, Dataset +from torch.utils.data.distributed import DistributedSampler, dist +from omegaconf import OmegaConf +from pathlib import Path +import os + +from gafl.data import utils as du +from gafl.analysis import utils as au +from gafl.analysis.metrics import calc_mdtraj_metrics + +class PdbDataModule(LightningDataModule): + def __init__(self, data_cfg): + super().__init__() + self.data_cfg = data_cfg + self.loader_cfg = data_cfg.loader + self.dataset_cfg = data_cfg.dataset + + OmegaConf.set_struct(self.dataset_cfg, False) + # Handle missing train_valid_test_split argument + if not hasattr(self.dataset_cfg, 'train_valid_test_split'): + self.dataset_cfg.train_valid_test_split = [1.0, 0.0, 0.0] + else: + assert sum(self.dataset_cfg.train_valid_test_split) == 1, 'train_valid_test_split must sum to 1' + assert len(self.dataset_cfg.train_valid_test_split) == 3, 'train_valid_test_split must have 3 elements' + + # Handle missing generate_valid_samples argument + if not hasattr(self.dataset_cfg, 'generate_valid_samples'): + self.dataset_cfg.generate_valid_samples = True + + if not hasattr(self.dataset_cfg, 'calc_dssp'): + self.dataset_cfg.calc_dssp = False + + if not hasattr(self.dataset_cfg, 'target_sec_content'): + self.dataset_cfg.target_sec_content = OmegaConf.create() + self.dataset_cfg.target_sec_content.helix_percent = 0.32 + self.dataset_cfg.target_sec_content.strand_percent = 0.27 + else: + if not hasattr(self.dataset_cfg.target_sec_content, 'helix_percent'): + self.dataset_cfg.target_sec_content.helix_percent = 0.32 + if not hasattr(self.dataset_cfg.target_sec_content, 'strand_percent'): + self.dataset_cfg.target_sec_content.strand_percent = 0.27 + + OmegaConf.set_struct(self.dataset_cfg, True) + + self.sampler_cfg = data_cfg.sampler + OmegaConf.set_struct(self.sampler_cfg, False) + if not hasattr(self.sampler_cfg, 'clustered'): + self.sampler_cfg.clustered = False + OmegaConf.set_struct(self.sampler_cfg, True) + + def setup(self, stage: str): + if self.dataset_cfg.calc_dssp: + pdb_csv = pd.read_csv(self.dataset_cfg.csv_path) + # Check if csc has columns helix_percent, strand_percent, coil_percent + if not ('helix_percent' in pdb_csv.columns and 'strand_percent' in pdb_csv.columns): + logging.info("Calculating DSSP values for dataset") + #Iterate over csv column 'processed_path' + helix_pct = [] + strand_pct = [] + coil_pct = [] + + for path in tqdm(pdb_csv['processed_path']): + try: + processed_feats = du.get_processed_feats(path) + + except Exception as e: + raise ValueError(f'Error in processing {path}') from e + + atom_pos = processed_feats['atom_positions'] + os.makedirs(os.path.join('tmp'), exist_ok=True) + au.write_prot_to_pdb(atom_pos, os.path.join('tmp', 'dssp_sample.pdb'), overwrite=True, no_indexing=True) + + #Calculate dssp + dssp = calc_mdtraj_metrics(os.path.join('tmp', 'dssp_sample.pdb')) + + helix_pct.append(dssp['helix_percent']) + strand_pct.append(dssp['strand_percent']) + coil_pct.append(dssp['coil_percent']) + + #Append dssp values to csv + pdb_csv['helix_percent'] = helix_pct + pdb_csv['strand_percent'] = strand_pct + pdb_csv['coil_percent'] = coil_pct + pdb_csv.to_csv(self.dataset_cfg.csv_path, index=False) + + self._train_dataset = PdbDataset( + dataset_cfg=self.dataset_cfg, + is_training=True, + ) + self._valid_dataset = PdbDataset( + dataset_cfg=self.dataset_cfg, + is_training=False, + ) + self._valid_sample_dataset = PdbDataset( + dataset_cfg=self.dataset_cfg, + is_training=False, + sample_dataset=True, + ) + + def train_dataloader(self, rank=None, num_replicas=None): + num_workers = self.loader_cfg.num_workers + batch_sampler = LengthBatcher( + sampler_cfg=self.sampler_cfg, + metadata_csv=self._train_dataset.csv, + rank=rank, + num_replicas=num_replicas, + num_batches=get_num_batches(self.sampler_cfg, self._train_dataset.csv), + ) + dataloader = DataLoader( + self._train_dataset, + batch_sampler=batch_sampler, + num_workers=num_workers, + prefetch_factor=None if num_workers == 0 else self.loader_cfg.prefetch_factor, + pin_memory=False, + persistent_workers=True if num_workers > 0 else False, + ) + + return dataloader + + def val_dataloader(self): + if self.dataset_cfg.generate_valid_samples: + valid_sample_loader = DataLoader( + self._valid_sample_dataset, + sampler=DistributedSampler(self._valid_sample_dataset, shuffle=False), + num_workers=2, + prefetch_factor=2, + persistent_workers=True, + ) + else: + valid_sample_loader = DataLoader(EmptyDataset(), batch_size=1) + + if self.dataset_cfg.train_valid_test_split[1] == 0: + valid_loader = DataLoader(EmptyDataset(), batch_size=1) + else: + num_workers = self.loader_cfg.num_workers + valid_loader = DataLoader( + self._valid_dataset, + batch_sampler=LengthBatcher( + sampler_cfg=self.sampler_cfg, + metadata_csv=self._valid_dataset.csv, + rank=None, + num_replicas=None, + num_batches=get_num_batches(self.sampler_cfg, self._valid_dataset.csv), + ), + num_workers=num_workers, + prefetch_factor=None if num_workers == 0 else self.loader_cfg.prefetch_factor, + pin_memory=False, + persistent_workers=True if num_workers > 0 else False, + ) + + return [valid_sample_loader, valid_loader] + +class PdbDataset(Dataset): + def __init__( + self, + *, + dataset_cfg, + is_training, + sample_dataset=False, # Determines if validation dataset should be used as template for sampling backbones in the validation step + ): + self._log = logging.getLogger(__name__) + self._is_training = is_training + self.sample_dataset = sample_dataset + self._dataset_cfg = dataset_cfg + + if not hasattr(self._dataset_cfg, 'filter_breaks'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.filter_breaks = False + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'label_breaks'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.label_breaks = False + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'use_res_idx'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.use_res_idx = False + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'break_csv_path'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.break_csv_path = self.dataset_cfg.csv_path.replace('metadata.csv', 'breaks.csv') + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'filter_scrmsd'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.filter_scrmsd = "inf" + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'max_coil_pct'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.max_coil_pct = 1. + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'min_num_res_eval'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.min_num_res_eval = 60 + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'allowed_oligomers'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.allowed_oligomers = None + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'apply_clustering'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.apply_clustering = False + OmegaConf.set_struct(self._dataset_cfg, True) + + if not hasattr(self._dataset_cfg, 'target_sec_content'): + OmegaConf.set_struct(self._dataset_cfg, False) + self._dataset_cfg.target_sec_content = OmegaConf.create() + self._dataset_cfg.target_sec_content.helix_percent = 0.32 + self._dataset_cfg.target_sec_content.strand_percent = 0.27 + OmegaConf.set_struct(self._dataset_cfg, True) + + + self._init_metadata() + self._rng = np.random.default_rng(seed=self._dataset_cfg.seed) + + @property + def is_training(self): + return self._is_training + + @property + def dataset_cfg(self): + return self._dataset_cfg + + def _init_metadata(self): + """Initialize metadata.""" + + # Process CSV with different filtering criterions. + pdb_csv = pd.read_csv(self.dataset_cfg.csv_path) + + # apply naming convention + pdb_csv = du.metadata_naming_convention(pdb_csv) + + if self.dataset_cfg.apply_clustering: + if hasattr(self.dataset_cfg, 'cluster_path_framediff'): + + # assume that the dataset type is framediff and read the clusters from the cluster file + logging.info("Reading and clusters from framdiff-like-cluster file and storing to metadata...\nIf you want to use the cluster present in the metadata, set cluster_path_framediff to null.") + pdb_to_cluster = _get_pdb_to_cluster_dict_framediff(self.dataset_cfg) + # store the cluster information in the metadata + cluster = [] + for pdb_name in pdb_csv['pdb_name']: + cluster.append(pdb_to_cluster[pdb_name] if pdb_name in pdb_to_cluster else "nan") + + unique_clusters = set(list(cluster)) + logging.info(f"Found {len(unique_clusters)} unique clusters.\n") + pdb_csv['cluster'] = cluster + + # define a filter mask that is used to filter the dataset + ############################### + filter_mask = [True] * len(pdb_csv) + + # filter for breaks (which we define as non-continuous residue indices) + if self.dataset_cfg.filter_breaks: + # Check if column "breaks" exists + if 'dist_breaks' not in pdb_csv.columns: + breaks = [] + for path in tqdm(pdb_csv['processed_path'], desc='Saving dist breaks in metadata...'): + chain_feats = self._process_csv_row(path) + + breaks.append(du.has_breaks(chain_feats) or du.has_inconstistent_indexing(chain_feats)) + pdb_csv['dist_breaks'] = breaks + pdb_csv.to_csv(self.dataset_cfg.csv_path, index=False) + + filter_mask_breaks = pdb_csv['dist_breaks'] == False + logging.info(f'Filtering for breaks: Removed {len(pdb_csv) - sum(filter_mask_breaks)} of {len(pdb_csv)} examples. {sum(filter_mask_breaks)} remaining.') + filter_mask = np.logical_and(filter_mask, filter_mask_breaks) + + # filter for scrmsd + if self.dataset_cfg.filter_scrmsd not in ["inf", "nan", float('inf'), float('nan'), None]: + max_scrmsd = float(self.dataset_cfg.filter_scrmsd) + # Check if column "scrmsd" exists or whether a csv file with scrmsd values is provided, then write the scrmsd values to the csv. + if 'scrmsd' not in pdb_csv.columns or hasattr(self.dataset_cfg, 'scrmsd_csv_path'): + assert hasattr(self.dataset_cfg, 'scrmsd_csv_path'), 'scrmsd_csv_path must be provided in the config if scrmsd column is not present in the csv.' + if not Path(self.dataset_cfg.scrmsd_csv_path).exists(): + raise FileNotFoundError(f"File {self.dataset_cfg.scrmsd_csv_path} not found. Set filter_scrmsd to 'inf' to ignore this error.") + scrmsd_csv = pd.read_csv(self.dataset_cfg.scrmsd_csv_path) + scrmsd_dict = {scrmsd_csv['pdb'][i]: scrmsd_csv['scrmsd'][i] for i in range(len(scrmsd_csv))} + scrmsd_values = [] + for pdb_name in pdb_csv['pdb_name']: + scrmsd_values.append(scrmsd_dict[pdb_name] if pdb_name in scrmsd_dict else "nan") + pdb_csv['scrmsd'] = scrmsd_values + pdb_csv.to_csv(self.dataset_cfg.csv_path, index=False) + + scrmsd_values = [float(v) if v != "nan" else float('inf') for v in pdb_csv['scrmsd']] + filter_mask_scrmsd = (np.array(scrmsd_values) <= max_scrmsd).tolist() + now_filtered_out = [filter_mask[i] and not filter_mask_scrmsd[i] for i in range(len(filter_mask))] + currently_remaining = sum(filter_mask) + filter_mask = np.logical_and(filter_mask, filter_mask_scrmsd) + + logging.info(f'Filtering for scrmsd < {max_scrmsd}. Removed {sum(now_filtered_out)} of {currently_remaining} examples. {sum(filter_mask)} remaining.') + + if self.dataset_cfg.max_coil_pct < 1.: + # Check if column "coil_pct" exists + assert 'coil_percent' in pdb_csv.columns, 'Column "coil_percent" must be present in the metadata csv. Cols: ' + str(pdb_csv.columns) + filter_mask_coil = pdb_csv['coil_percent'] <= self.dataset_cfg.max_coil_pct + + now_filtered_out = [filter_mask[i] and not filter_mask_coil[i] for i in range(len(filter_mask))] + currently_remaining = sum(filter_mask) + filter_mask = np.logical_and(filter_mask, filter_mask_coil) + logging.info(f'Filtering for coil_pct <= {self.dataset_cfg.max_coil_pct}. Removed {sum(now_filtered_out)} of {currently_remaining} examples. {sum(filter_mask)} remaining.') + + # oligomer filter (if not in metadata cols, assume all are monomeric) + if self.dataset_cfg.allowed_oligomers is not None: + if self.dataset_cfg.allowed_oligomers != ['monomeric'] and not 'oligomeric_detail' in pdb_csv.columns: + raise ValueError('Column "oligomeric_detail" must be present in the metadata csv if allowed_oligomers is set.') + allowed_oligomers = self.dataset_cfg.allowed_oligomers + if 'oligomeric_detail' in pdb_csv.columns: + filter_mask_oligomers = pdb_csv['oligomeric_detail'].isin(allowed_oligomers) + now_filtered_out = [filter_mask[i] and not filter_mask_oligomers[i] for i in range(len(filter_mask))] + currently_remaining = sum(filter_mask) + filter_mask = np.logical_and(filter_mask, filter_mask_oligomers) + logging.info(f'Filtering for allowed oligomers: Removed {sum(now_filtered_out)} of {currently_remaining} examples. {sum(filter_mask)} remaining.') + ############################### + + + # Process information of breaks (unmodelled residues) in the pdb files + ############################### + # be default, assume that the break path is metadata_path.parent/breaks.csv: + if self.dataset_cfg.label_breaks or self.dataset_cfg.use_res_idx: + if self.dataset_cfg.break_csv_path is None: + self.dataset_cfg.break_csv_path = str(Path(self.dataset_cfg.csv_path).parent/'breaks.csv') + logging.info(f'data.dataset.break_csv_path is None. Setting it to data.dataset.csv_path.parent/breaks.csv, i.e. {self.dataset_cfg.break_csv_path}') + if os.path.exists(self.dataset_cfg.break_csv_path): + logging.info(f'Loading break information from self.dataset_cfg.break_csv_path={self.dataset_cfg.break_csv_path}') + self.break_csv = pd.read_csv(self.dataset_cfg.break_csv_path) + else: + logging.info('Found no break information at self.dataset_cfg.break_csv_path') + logging.info(f'Calculating breaks for dataset and storing them at {self.dataset_cfg.break_csv_path}...') + + breaks_dict = { + 'pdb_name': [], + 'idx_breaks': [], + 'dist_breaks': [], + 'merged_idx': [], + 'consistent_breaks': [] + } + + for i in tqdm(range(len(pdb_csv)), desc='Calculating positions of breaks'): + csv_row = pdb_csv.iloc[i] + data = self._process_csv_row(csv_row['processed_path']) + idx1 = du.idx_breaks(data) + idx2 = du.dist_breaks(data) + merged_idx = np.unique(np.concatenate((idx1, idx2))) + # True if IDX and DIST criteriums for breaks are met at the same time + consistent_breaks = np.array_equal(idx1, idx2) + breaks_dict['pdb_name'].append(csv_row['pdb_name']) + breaks_dict['idx_breaks'].append(list(idx1)) + breaks_dict['dist_breaks'].append(list(idx2)) + breaks_dict['merged_idx'].append(list(merged_idx)) + breaks_dict['consistent_breaks'].append(consistent_breaks) + + self.break_csv = pd.DataFrame(breaks_dict) + self.break_csv.to_csv(self.dataset_cfg.break_csv_path, index=False) + + ############################### + + + # Note: pdb_csv is the stored csv file with all samples and most relevant columns, self.csv will be a) filtered and b) appended by additional columns like break information etc. + self.csv = pdb_csv + if self.dataset_cfg.use_res_idx or self.dataset_cfg.label_breaks: + self.csv = self.csv.merge(self.break_csv, on='pdb_name') + + # apply filtering: + if not isinstance(filter_mask, list): + filter_mask = filter_mask.tolist() + + self.csv = self.csv[filter_mask] + self.csv = self.csv.reset_index(drop=True) + + logging.info(f'Number of examples after filtering: {len(pdb_csv)}\n') + # Filter for modeled sequence length. + self.csv = self.csv[self.csv.modeled_seq_len <= self.dataset_cfg.max_num_res] + self.csv = self.csv[self.csv.modeled_seq_len >= self.dataset_cfg.min_num_res] + + logging.info(f'Number of examples after filtering for modeled sequence length: {len(self.csv)}\n') + + if self.dataset_cfg.subset is not None: + self.csv = self.csv.iloc[:self.dataset_cfg.subset] + + if self.dataset_cfg.calc_dssp: + self.helix_percent = np.mean(self.csv['helix_percent'].to_numpy()) + self.strand_percent = np.mean(self.csv['strand_percent'].to_numpy()) + else: + self.helix_percent = self.dataset_cfg.target_sec_content.helix_percent + self.strand_percent = self.dataset_cfg.target_sec_content.strand_percent + + # Training or validation specific logic. + if self.is_training: + logging.info(f'Using {self.helix_percent} helix and {self.strand_percent} strand content as target secondary structure content') + + # Extract training set. + if self.dataset_cfg.train_valid_test_split[0] != 1.0: + self.csv = self.csv.groupby('modeled_seq_len') + self.csv = self.csv.apply(lambda x: x.sample(frac=self.dataset_cfg.train_valid_test_split[0], replace=False, random_state=self.dataset_cfg.seed)).droplevel(0) + self.csv = self.csv.sort_values('modeled_seq_len', ascending=False) + self._log.info( + f'Training: {len(self.csv)} examples') + else: + self.csv = self.csv.sort_values('modeled_seq_len', ascending=False) + else: + if self.sample_dataset: + mask = self.csv['modeled_seq_len'] >= self.dataset_cfg.min_num_res_eval + mask &= self.csv['modeled_seq_len'] <= self.dataset_cfg.min_eval_length + eval_csv = self.csv[mask] + eval_csv = eval_csv.sort_values('modeled_seq_len', ascending=False) + all_lengths = np.sort(eval_csv.modeled_seq_len.unique()) + length_indices = (len(all_lengths) - 1) * np.linspace( + 0.0, 1.0, self.dataset_cfg.num_eval_lengths) + length_indices = length_indices.astype(int) + eval_lengths = all_lengths[length_indices] + eval_csv = eval_csv[eval_csv.modeled_seq_len.isin(eval_lengths)] + + # Fix a random seed to get the same split each time. + eval_csv = eval_csv.groupby('modeled_seq_len').sample( + self.dataset_cfg.samples_per_eval_length, replace=True, random_state=123) + eval_csv = eval_csv.sort_values('modeled_seq_len', ascending=False) + self.csv = eval_csv + if self.dataset_cfg.generate_valid_samples: + self._log.info( + f'Generate {len(self.csv)} validation samples with lengths {eval_lengths}') + else: + # Extract validation set. + if self.dataset_cfg.train_valid_test_split[1] > 0: + valid_frac = self.dataset_cfg.train_valid_test_split[1] / (self.dataset_cfg.train_valid_test_split[1] + self.dataset_cfg.train_valid_test_split[2]) + else: + self.csv = None + return + + train_csv = self.csv.groupby('modeled_seq_len') + self.train_csv = train_csv.apply(lambda x: x.sample(frac=self.dataset_cfg.train_valid_test_split[0], replace=False, random_state=self.dataset_cfg.seed)).droplevel(0) + self.csv = self.csv.drop(train_csv.index) + self.csv = self.csv.groupby('modeled_seq_len') + self.csv = self.csv.apply(lambda x: x.sample(frac=valid_frac, replace=False, random_state=self.dataset_cfg.seed)).droplevel(0) + self.csv = self.csv.sort_values('modeled_seq_len', ascending=False) + self._log.info(f'Validation: {len(self.csv)} examples') + + def _process_csv_row(self, processed_file_path): + try: + processed_feats = du.get_processed_feats(processed_file_path) + modeled_idx = processed_feats['modeled_idx'] + if len(modeled_idx) == 0: + raise ValueError(f'No modeled residues found in {processed_file_path}') + + # Filter out residues that are not modeled. + min_idx = np.min(modeled_idx) + max_idx = np.max(modeled_idx) + processed_feats = tree.map_structure( + lambda x: x[min_idx:(max_idx+1)], processed_feats) + + # Run through OpenFold data transforms. + chain_feats = { + 'aatype': torch.tensor(processed_feats['aatype']).long(), + 'all_atom_positions': torch.tensor(processed_feats['atom_positions']).double(), + 'all_atom_mask': torch.tensor(processed_feats['atom_mask']).double() + } + chain_feats = data_transforms.atom37_to_frames(chain_feats) + rigids_1 = rigid_utils.Rigid.from_tensor_4x4(chain_feats['rigidgroups_gt_frames'])[:, 0] + rotmats_1 = rigids_1.get_rots().get_rot_mats() + trans_1 = rigids_1.get_trans() + res_idx = processed_feats['residue_index'] + res_idx = res_idx - np.min(res_idx) + 1 + + except Exception as e: + raise ValueError(f'Error in processing {processed_file_path}') from e + + return { + 'aatype': chain_feats['aatype'], + 'res_idx': torch.tensor(res_idx), + 'rotmats_1': rotmats_1, + 'trans_1': trans_1, + 'res_mask': torch.tensor(processed_feats['bb_mask']).int(), + 'atom_positions': chain_feats['all_atom_positions'], + } + + def __len__(self): + return len(self.csv) + + def __getitem__(self, idx, conf_idx:int=None): + # Sample data example. + example_idx = idx + if isinstance(example_idx, list): + example_idx = example_idx[0] + + csv_row = self.csv.iloc[example_idx] + processed_file_path = csv_row['processed_path'] + chain_feats = self._process_csv_row(processed_file_path) + chain_feats['csv_idx'] = torch.ones(1, dtype=torch.long) * idx + + if self.dataset_cfg.use_res_idx: + # If there are inconsistencies in the different break definitions, consecutive residue indices are used + if (not csv_row['consistent_breaks']): + chain_feats['res_idx'] = torch.arange(chain_feats['res_mask'].shape[0], dtype=torch.long) + else: + chain_feats['res_idx'] = torch.arange(chain_feats['res_mask'].shape[0], dtype=torch.long) + + if self.dataset_cfg.label_breaks: + break_mask = torch.zeros(chain_feats['res_mask'].shape[0], dtype=torch.float32) + break_idc = csv_row['merged_idx'] + # if there are no breaks, break_idc is empty, so we can leave the mask as it is + if len(break_idc) > 0: + if isinstance(break_idc, str): + break_idc = ast.literal_eval(break_idc) + break_idc = np.array(break_idc, dtype=np.int32) + break_idc = np.append(break_idc, break_idc + 1) + #Create tensor of length N with 1 at break positions + break_mask[break_idc] = 1.0 + + chain_feats['breaks'] = break_mask + + if not self.is_training: + chain_feats['target_helix_percent'] = self.helix_percent + chain_feats['target_strand_percent'] = self.strand_percent + + return chain_feats + + +class LengthBatcher: + + def __init__( + self, + *, + sampler_cfg, + metadata_csv, + seed=123, + shuffle=True, + num_replicas=None, + rank=None, + num_batches=None, + ): + """ + If clustered: Assumes that there is an entry "cluster" in the metadata, for which a unique identifier is expected. Then, an epoch is defined as iteration over all clusters, where for each epoch, one random cluster member is picked. + """ + # In FrameFlow, each epoch had n_data batches, so the data points were seen multiple times per epoch. + # here, we define epoch as the iteration over all data points once. + super().__init__() + self._log = logging.getLogger(__name__) + if num_replicas is None: + self.num_replicas = dist.get_world_size() + else: + self.num_replicas = num_replicas + if rank is None: + self.rank = dist.get_rank() + else: + self.rank = rank + + self._sampler_cfg = sampler_cfg + self._data_csv = metadata_csv + self._cluster_init() + self._data_csv['index'] = list(range(len(self._data_csv))) + self.seed = seed + self.shuffle = shuffle + self.epoch = 0 + self.max_batch_size = self._sampler_cfg.max_batch_size + self._log.info(f'Created dataloader rank {self.rank+1} out of {self.num_replicas}') + + # OUTCOMMENTED BECAUSE DDP REQUIRES SAME NUM BATCHES ACROSS ALL REPLICAS! + ############################### + # # set max num batches to be the number of batches in epoch 0. + # self.num_batches = None + # self._create_batches() + # self.num_batches = len(self.sample_order) + ############################### + + + self.num_batches = num_batches + if num_batches is not None: + self.num_batches = num_batches//self.num_replicas + self._log.info(f'Total number of batches: {self.num_batches}') + self._log.info(f'Number of batches per replica: {self.num_batches}') + + def _cluster_init(self): + self.clustered = self._sampler_cfg.clustered if hasattr(self._sampler_cfg, 'clustered') else False + if self.clustered: + if not 'cluster' in self._data_csv.columns: + raise ValueError("Clustered sampling requires a 'cluster' column in the metadata.") + + def _cluster_unassigned(cluster_id): + if cluster_id in ["", "None", "nan", None]: + return True + if isinstance(cluster_id, float) or isinstance(cluster_id, int): + return np.isnan(cluster_id) + return False + + # assign clusters to states that have no valid cluster entry in the metadata.csv: + for i, row in self._data_csv.iterrows(): + if _cluster_unassigned(row['cluster']): + new_cluster = hash(str(i)) # assume that this does not occur twice + self._data_csv.at[i, 'cluster'] = new_cluster + + elif not isinstance(row['cluster'], str): + if float(row['cluster']).is_integer(): + self._data_csv.at[i, 'cluster'] = int(row['cluster']) + else: + raise ValueError(f"Cluster must be a string or integer-like float. Found {row['cluster']} in {row['pdb_name']}.") + + + all_clusters = self._data_csv['cluster'].unique() + has_nan_cluster = any([cluster == "nan" for cluster in all_clusters]) + if has_nan_cluster and len(all_clusters) == 1: + raise RuntimeError("Internal error. All clusters are nan.") + if has_nan_cluster: + logging.warning(f"Found nan cluster among {len(all_clusters)} clusters. This will be treated as a separate cluster.") + + # dictionary that maps cluster to a list of csv indices that belong to that cluster + self.cluster_dict = {cluster: self._data_csv[self._data_csv['cluster'] == cluster].index.tolist() for cluster in all_clusters} + assert sum([len(self.cluster_dict[cluster]) for cluster in self.cluster_dict]) == len(self._data_csv), "Internal error. Not all indices are assigned to a cluster." + + logging.info(f'Applying clustered sampling: {len(all_clusters)} clusters, {len(self._data_csv)} examples.') + + + def _get_replica_csv(self, rng:torch.Generator): + replica_csv = self._data_csv + + if self.clustered: + np_rng = np.random.default_rng(seed=int(rng.initial_seed())) + # for each cluster, choose a random member and write it to replica_csv + cluster_indices = [] + for cluster in self.cluster_dict: + cluster_indices.append(np_rng.choice(self.cluster_dict[cluster], size=1)[0]) + + replica_csv = replica_csv[replica_csv.index.isin(cluster_indices)] + + # indices are only used for randomly splitting the batch across devices + indices = list(range(len(replica_csv))) + + if self.shuffle: + indices = torch.randperm(len(indices), generator=rng).tolist() + + # replica csv is a reordered version (and for num_replicas > 1 also subset of) the original csv + if len(indices) > self.num_replicas: + replica_csv = replica_csv.iloc[ + indices[self.rank::self.num_replicas] + ] + + return replica_csv + + + def _replica_epoch_batches(self): + """ + Returns the batch idxs for the current epoch. + """ + # Make sure all replicas share the same seed on each epoch. + rng = torch.Generator() + rng.manual_seed(self.seed + self.epoch) + + replica_csv = self._get_replica_csv(rng) + + # Each batch contains multiple proteins of the same length. + sample_order = [] + for seq_len, len_df in replica_csv.groupby('modeled_seq_len'): + max_batch_size = min( + self.max_batch_size, + self._sampler_cfg.max_num_res_squared // seq_len**2 + 1, + ) + num_batches = math.ceil(len(len_df) / max_batch_size) + for i in range(num_batches): + batch_df = len_df.iloc[i*max_batch_size:(i+1)*max_batch_size] + batch_indices = batch_df['index'].tolist() + sample_order.append(batch_indices) + + # Remove any length bias. + new_order = torch.randperm(len(sample_order), generator=rng).numpy().tolist() + return [sample_order[i] for i in new_order] + + # def _create_batches(self): + # # Make sure all replicas have the same number of batches Otherwise leads to bugs. + # # See bugs with shuffling https://github.com/Lightning-AI/lightning/issues/10947 + # all_batches = [] + # num_augments = -1 + # while len(all_batches) < self._num_batches: + # all_batches.extend(self._replica_epoch_batches()) + # num_augments += 1 + # if num_augments > 1000: + # raise ValueError('Exceeded number of augmentations.') + # if len(all_batches) >= self._num_batches: + # all_batches = all_batches[:self._num_batches] + # self.sample_order = all_batches + + def _create_batches(self): + # Make sure all replicas have the same number of batches Otherwise leads to bugs. + # See bugs with shuffling https://github.com/Lightning-AI/lightning/issues/10947 + all_batches = self._replica_epoch_batches() + if self.num_batches is not None: + if len(all_batches) > self.num_batches: + all_batches = all_batches[:self.num_batches] + elif len(all_batches) < self.num_batches: + # randomly duplicate batches to match the number of batches + duplicates = np.random.choice(len(all_batches), size=self.num_batches - len(all_batches), replace=True) + all_batches.extend([all_batches[d] for d in duplicates]) + else: + raise ValueError("num_batches must be set before creating batches") + self.sample_order = all_batches + + + def __iter__(self): + self._create_batches() + self.epoch += 1 + return iter(self.sample_order) + + def __len__(self): + return self.num_batches + + +def get_num_batches(sampler_cfg, metadata_csv, seed=123): + """ + Function to infer the number of batches in an epoch. This can be used for automatically inferring the approx. (exact number is epoch-dependent) total number of batches for LengthBatcher. Has to be called before initializing the actual distributed samplers since the number of batches has to be the same across all replicas. + """ + # create a dummy length batcher with num_replicas=1: + batcher = LengthBatcher( + sampler_cfg=sampler_cfg, + metadata_csv=metadata_csv, + seed=seed, + shuffle=True, + num_replicas=1, + rank=0, + num_batches=None + ) + all_batches = batcher._replica_epoch_batches() + return len(all_batches) + + +class EmptyDataset(Dataset): + def __len__(self): + return 0 + + def __getitem__(self, idx): + raise IndexError("This dataset is empty") + + + +def _read_clusters_framediff(dataset_cfg): + pdb_to_cluster = {} + with open(dataset_cfg.cluster_path_framediff, "r") as f: + for i,line in enumerate(f): + for chain in line.split(' '): + pdb = chain.split('_')[0] + pdb_to_cluster[pdb.lower()] = str(i) + return pdb_to_cluster + +def _get_pdb_to_cluster_dict_framediff(dataset_cfg): + pdb_to_cluster = _read_clusters_framediff(dataset_cfg) + return pdb_to_cluster diff --git a/gafl/gafl/data/process_pdb_files.py b/gafl/gafl/data/process_pdb_files.py new file mode 100644 index 0000000000000000000000000000000000000000..9037f7c41b65ed72d65da6493e8c9d2ad64a6e01 --- /dev/null +++ b/gafl/gafl/data/process_pdb_files.py @@ -0,0 +1,211 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Script for preprocessing PDB files.""" + +import argparse +import dataclasses +import functools as fn +import pandas as pd +import os +import multiprocessing as mp +import time +from Bio import PDB +import numpy as np +import mdtraj as md + + +from gafl.data import utils as du +from gafl.data import parsers +from gafl.data import errors + + +# Define the parser +parser = argparse.ArgumentParser( + description='PDB processing script.') +parser.add_argument( + '--pdb_dir', + help='Path to directory with PDB files.', + type=str) +parser.add_argument( + '--num_processes', + help='Number of processes.', + type=int, + default=50) +parser.add_argument( + '--write_dir', + help='Path to write results to.', + type=str, + default='preprocessed') +parser.add_argument( + '--debug', + help='Turn on for debugging.', + action='store_true') +parser.add_argument( + '--verbose', + help='Whether to log everything.', + action='store_true') + + +def process_file(file_path: str, write_dir: str): + """Processes protein file into usable, smaller pickles. + + Args: + file_path: Path to file to read. + write_dir: Directory to write pickles to. + + Returns: + Saves processed protein to pickle and returns metadata. + + Raises: + DataError if a known filtering rule is hit. + All other errors are unexpected and are propogated. + """ + metadata = {} + pdb_name = os.path.basename(file_path).replace('.pdb', '') + metadata['pdb_name'] = pdb_name + + processed_path = os.path.join(write_dir, f'{pdb_name}.pkl') + metadata['processed_path'] = os.path.abspath(processed_path) + metadata['raw_path'] = file_path + parser = PDB.PDBParser(QUIET=True) + structure = parser.get_structure(pdb_name, file_path) + + # Extract all chains + struct_chains = { + chain.id.upper(): chain + for chain in structure.get_chains()} + metadata['num_chains'] = len(struct_chains) + + # Extract features + struct_feats = [] + all_seqs = set() + for chain_id, chain in struct_chains.items(): + # Convert chain id into int + chain_id = du.chain_str_to_int(chain_id) + chain_prot = parsers.process_chain(chain, chain_id) + chain_dict = dataclasses.asdict(chain_prot) + chain_dict = du.parse_chain_feats(chain_dict) + all_seqs.add(tuple(chain_dict['aatype'])) + struct_feats.append(chain_dict) + if len(all_seqs) == 1: + metadata['quaternary_category'] = 'homomer' + else: + metadata['quaternary_category'] = 'heteromer' + complex_feats = du.concat_np_features(struct_feats, False) + + # Process geometry features + complex_aatype = complex_feats['aatype'] + metadata['seq_len'] = len(complex_aatype) + modeled_idx = np.where(complex_aatype != 20)[0] + if np.sum(complex_aatype != 20) == 0: + raise errors.LengthError('No modeled residues') + min_modeled_idx = np.min(modeled_idx) + max_modeled_idx = np.max(modeled_idx) + metadata['modeled_seq_len'] = max_modeled_idx - min_modeled_idx + 1 + complex_feats['modeled_idx'] = modeled_idx + + try: + # MDtraj + traj = md.load(file_path) + # SS calculation + pdb_ss = md.compute_dssp(traj, simplified=True) + # DG calculation + pdb_dg = md.compute_rg(traj) + os.remove(file_path) + except Exception as e: + os.remove(file_path) + raise errors.DataError(f'Mdtraj failed with error {e}') + + chain_dict['ss'] = pdb_ss[0] + metadata['coil_percent'] = np.sum(pdb_ss == 'C') / metadata['modeled_seq_len'] + metadata['helix_percent'] = np.sum(pdb_ss == 'H') / metadata['modeled_seq_len'] + metadata['strand_percent'] = np.sum(pdb_ss == 'E') / metadata['modeled_seq_len'] + + # Radius of gyration + metadata['radius_gyration'] = pdb_dg[0] + + # Write features to pickles. + du.write_pkl(processed_path, complex_feats) + + # Return metadata + return metadata + + +def process_serially(all_paths, write_dir): + all_metadata = [] + for i, file_path in enumerate(all_paths): + try: + start_time = time.time() + metadata = process_file( + file_path, + write_dir) + elapsed_time = time.time() - start_time + print(f'Finished {file_path} in {elapsed_time:2.2f}s') + all_metadata.append(metadata) + except errors.DataError as e: + print(f'Failed {file_path}: {e}') + return all_metadata + + +def process_fn( + file_path, + verbose=None, + write_dir=None): + try: + start_time = time.time() + metadata = process_file( + file_path, + write_dir) + elapsed_time = time.time() - start_time + if verbose: + print(f'Finished {file_path} in {elapsed_time:2.2f}s') + return metadata + except errors.DataError as e: + if verbose: + print(f'Failed {file_path}: {e}') + + +def main(args): + pdb_dir = args.pdb_dir + all_file_paths = [ + os.path.join(pdb_dir, x) + for x in os.listdir(args.pdb_dir) if '.pdb' in x] + total_num_paths = len(all_file_paths) + write_dir = args.write_dir + if not os.path.exists(write_dir): + os.makedirs(write_dir) + if args.debug: + metadata_file_name = 'metadata_debug.csv' + else: + metadata_file_name = 'metadata.csv' + metadata_path = os.path.join(write_dir, metadata_file_name) + print(f'Files will be written to {write_dir}') + + # Process each mmcif file + if args.num_processes == 1 or args.debug: + all_metadata = process_serially( + all_file_paths, + write_dir) + else: + _process_fn = fn.partial( + process_fn, + verbose=args.verbose, + write_dir=write_dir) + with mp.Pool(processes=args.num_processes) as pool: + all_metadata = pool.map(_process_fn, all_file_paths) + all_metadata = [x for x in all_metadata if x is not None] + metadata_df = pd.DataFrame(all_metadata) + metadata_df.to_csv(metadata_path, index=False) + succeeded = len(all_metadata) + print( + f'Finished processing {succeeded}/{total_num_paths} files') + + +if __name__ == "__main__": + # Don't use GPU + os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" + os.environ["CUDA_VISIBLE_DEVICES"] = "" + args = parser.parse_args() + main(args) \ No newline at end of file diff --git a/gafl/gafl/data/protein.py b/gafl/gafl/data/protein.py new file mode 100644 index 0000000000000000000000000000000000000000..9f296eb60b2d7a2a0a899730f61413f53aa12e39 --- /dev/null +++ b/gafl/gafl/data/protein.py @@ -0,0 +1,296 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Protein data type.""" +import dataclasses +import io +from typing import Any, Mapping, Optional +from Bio.PDB import PDBParser +import numpy as np +import mdtraj as md + +from gafl.data import residue_constants + + +FeatureDict = Mapping[str, np.ndarray] +ModelOutput = Mapping[str, Any] # Is a nested dict. + +# Complete sequence of chain IDs supported by the PDB format. +PDB_CHAIN_IDS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' +PDB_MAX_CHAINS = len(PDB_CHAIN_IDS) # := 62. + + +@dataclasses.dataclass(frozen=True) +class Protein: + """Protein structure representation.""" + + # Cartesian coordinates of atoms in angstroms. The atom types correspond to + # residue_constants.atom_types, i.e. the first three are N, CA, CB. + atom_positions: np.ndarray # [num_res, num_atom_type, 3] + + # Amino-acid type for each residue represented as an integer between 0 and + # 20, where 20 is 'X'. + aatype: np.ndarray # [num_res] + + # Binary float mask to indicate presence of a particular atom. 1.0 if an atom + # is present and 0.0 if not. This should be used for loss masking. + atom_mask: np.ndarray # [num_res, num_atom_type] + + # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. + residue_index: np.ndarray # [num_res] + + # 0-indexed number corresponding to the chain in the protein that this residue + # belongs to. + chain_index: np.ndarray # [num_res] + + # B-factors, or temperature factors, of each residue (in sq. angstroms units), + # representing the displacement of the residue from its ground truth mean + # value. + b_factors: np.ndarray # [num_res, num_atom_type] + + dssp: np.ndarray = None # [num_res]; optional & computed with mdtraj + + def __post_init__(self): + if len(np.unique(self.chain_index)) > PDB_MAX_CHAINS: + raise ValueError( + f'Cannot build an instance with more than {PDB_MAX_CHAINS} chains ' + 'because these cannot be written to PDB format.') + + +def from_pdb_string(pdb_str: str, chain_id: Optional[str] = None, calc_dssp:bool=False) -> Protein: + """Takes a PDB string and constructs a Protein object. + + WARNING: All non-standard residue types will be converted into UNK. All + non-standard atoms will be ignored. + + Args: + pdb_str: The contents of the pdb file + chain_id: If chain_id is specified (e.g. A), then only that chain + is parsed. Otherwise all chains are parsed. + + Returns: + A new `Protein` parsed from the pdb contents. + + Modified: + included a dssp entry in the Protein object to store the secondary structure information + """ + pdb_fh = io.StringIO(pdb_str) + parser = PDBParser(QUIET=True) + structure = parser.get_structure('none', pdb_fh) + models = list(structure.get_models()) + if len(models) != 1: + raise ValueError( + f'Only single model PDBs are supported. Found {len(models)} models.') + model = models[0] + + atom_positions = [] + aatype = [] + atom_mask = [] + residue_index = [] + chain_ids = [] + b_factors = [] + if calc_dssp: + t = md.load(pdb_str) + dssp = md.compute_dssp(t) + dssp = dssp[0] + else: + dssp = None + + for chain in model: + if chain_id is not None and chain.id != chain_id: + continue + for res in chain: + if res.id[2] != ' ': + raise ValueError( + f'PDB contains an insertion code at chain {chain.id} and residue ' + f'index {res.id[1]}. These are not supported.') + res_shortname = residue_constants.restype_3to1.get(res.resname, 'X') + restype_idx = residue_constants.restype_order.get( + res_shortname, residue_constants.restype_num) + pos = np.zeros((residue_constants.atom_type_num, 3)) + mask = np.zeros((residue_constants.atom_type_num,)) + res_b_factors = np.zeros((residue_constants.atom_type_num,)) + for atom in res: + if atom.name not in residue_constants.atom_types: + continue + pos[residue_constants.atom_order[atom.name]] = atom.coord + mask[residue_constants.atom_order[atom.name]] = 1. + res_b_factors[residue_constants.atom_order[atom.name]] = atom.bfactor + if np.sum(mask) < 0.5: + # If no known atom positions are reported for the residue then skip it. + continue + aatype.append(restype_idx) + atom_positions.append(pos) + atom_mask.append(mask) + residue_index.append(res.id[1]) + chain_ids.append(chain.id) + b_factors.append(res_b_factors) + + # Chain IDs are usually characters so map these to ints. + unique_chain_ids = np.unique(chain_ids) + chain_id_mapping = {cid: n for n, cid in enumerate(unique_chain_ids)} + chain_index = np.array([chain_id_mapping[cid] for cid in chain_ids]) + + return Protein( + atom_positions=np.array(atom_positions), + atom_mask=np.array(atom_mask), + aatype=np.array(aatype), + residue_index=np.array(residue_index), + chain_index=chain_index, + b_factors=np.array(b_factors), + dssp=dssp) + + + +def _chain_end(atom_index, end_resname, chain_name, residue_index) -> str: + chain_end = 'TER' + return (f'{chain_end:<6}{atom_index:>5} {end_resname:>3} ' + f'{chain_name:>1}{residue_index:>4}') + + +def to_pdb(prot: Protein, model=1, add_end=True) -> str: + """Converts a `Protein` instance to a PDB string. + + Args: + prot: The protein to convert to PDB. + + Returns: + PDB string. + """ + restypes = residue_constants.restypes + ['X'] + res_1to3 = lambda r: residue_constants.restype_1to3.get(restypes[r], 'UNK') + atom_types = residue_constants.atom_types + + pdb_lines = [] + + atom_mask = prot.atom_mask + aatype = prot.aatype + atom_positions = prot.atom_positions + residue_index = prot.residue_index.astype(int) + chain_index = prot.chain_index.astype(int) + b_factors = prot.b_factors + + if np.any(aatype > residue_constants.restype_num): + raise ValueError('Invalid aatypes.') + + # Construct a mapping from chain integer indices to chain ID strings. + chain_ids = {} + for i in np.unique(chain_index): # np.unique gives sorted output. + if i >= PDB_MAX_CHAINS: + raise ValueError( + f'The PDB format supports at most {PDB_MAX_CHAINS} chains.') + chain_ids[i] = PDB_CHAIN_IDS[i] + + pdb_lines.append(f'MODEL {model}') + atom_index = 1 + last_chain_index = chain_index[0] + # Add all atom sites. + for i in range(aatype.shape[0]): + # Close the previous chain if in a multichain PDB. + if last_chain_index != chain_index[i]: + pdb_lines.append(_chain_end( + atom_index, res_1to3(aatype[i - 1]), chain_ids[chain_index[i - 1]], + residue_index[i - 1])) + last_chain_index = chain_index[i] + atom_index += 1 # Atom index increases at the TER symbol. + + res_name_3 = res_1to3(aatype[i]) + for atom_name, pos, mask, b_factor in zip( + atom_types, atom_positions[i], atom_mask[i], b_factors[i]): + if mask < 0.5: + continue + + record_type = 'ATOM' + name = atom_name if len(atom_name) == 4 else f' {atom_name}' + alt_loc = '' + insertion_code = '' + occupancy = 1.00 + element = atom_name[0] # Protein supports only C, N, O, S, this works. + charge = '' + # PDB is a columnar format, every space matters here! + atom_line = (f'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}' + f'{res_name_3:>3} {chain_ids[chain_index[i]]:>1}' + f'{residue_index[i]:>4}{insertion_code:>1} ' + f'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}' + f'{occupancy:>6.2f}{b_factor:>6.2f} ' + f'{element:>2}{charge:>2}') + pdb_lines.append(atom_line) + atom_index += 1 + + # Close the final chain. + pdb_lines.append(_chain_end(atom_index, res_1to3(aatype[-1]), + chain_ids[chain_index[-1]], residue_index[-1])) + pdb_lines.append('ENDMDL') + if add_end: + pdb_lines.append('END') + + # Pad all lines to 80 characters. + pdb_lines = [line.ljust(80) for line in pdb_lines] + return '\n'.join(pdb_lines) + '\n' # Add terminating newline. + + +def ideal_atom_mask(prot: Protein) -> np.ndarray: + """Computes an ideal atom mask. + + `Protein.atom_mask` typically is defined according to the atoms that are + reported in the PDB. This function computes a mask according to heavy atoms + that should be present in the given sequence of amino acids. + + Args: + prot: `Protein` whose fields are `numpy.ndarray` objects. + + Returns: + An ideal atom mask. + """ + return residue_constants.STANDARD_ATOM_MASK[prot.aatype] + + +def from_prediction( + features: FeatureDict, + result: ModelOutput, + b_factors: Optional[np.ndarray] = None, + remove_leading_feature_dimension: bool = True) -> Protein: + """Assembles a protein from a prediction. + + Args: + features: Dictionary holding model inputs. + result: Dictionary holding model outputs. + b_factors: (Optional) B-factors to use for the protein. + remove_leading_feature_dimension: Whether to remove the leading dimension + of the `features` values. + + Returns: + A protein instance. + """ + fold_output = result['structure_module'] + + def _maybe_remove_leading_dim(arr: np.ndarray) -> np.ndarray: + return arr[0] if remove_leading_feature_dimension else arr + + if 'asym_id' in features: + chain_index = _maybe_remove_leading_dim(features['asym_id']) + else: + chain_index = np.zeros_like(_maybe_remove_leading_dim(features['aatype'])) + + if b_factors is None: + b_factors = np.zeros_like(fold_output['final_atom_mask']) + + return Protein( + aatype=_maybe_remove_leading_dim(features['aatype']), + atom_positions=fold_output['final_atom_positions'], + atom_mask=fold_output['final_atom_mask'], + residue_index=_maybe_remove_leading_dim(features['residue_index']) + 1, + chain_index=chain_index, + b_factors=b_factors) \ No newline at end of file diff --git a/gafl/gafl/data/quarternion_utils.py b/gafl/gafl/data/quarternion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a42ed879a0cf18b2e2ab05c8fd542163bef2fc --- /dev/null +++ b/gafl/gafl/data/quarternion_utils.py @@ -0,0 +1,61 @@ +# Copyright (c) 2024 HITS gGmbH + +# replace the quaternion calculation of openfold by a version that does not use torch.eigh and is thus differentiable wrt the rotation matrices. + +import torch + +def rot_to_quat(rot): + if rot.shape[-2:] != (3, 3): + raise ValueError("Input rotation matrix must be of shape [..., 3, 3]") + + orig_shape = rot.shape + + rot = rot.view(-1, 3, 3) + + # Compute the trace of the rotation matrices + r_trace = rot[:, 0, 0] + rot[:, 1, 1] + rot[:, 2, 2] + + # Preallocate the quaternion tensor with zeros + q = torch.zeros(rot.shape[:-2] + (4,), dtype=rot.dtype, device=rot.device) + + # Determine conditions for each case + case1 = r_trace > 0 + case2 = (rot[:, 0, 0] > rot[:, 1, 1]) & (rot[:, 0, 0] > rot[:, 2, 2]) & ~case1 + case3 = (rot[:, 1, 1] > rot[:, 2, 2]) & ~case1 & ~case2 + case4 = ~(case1 | case2 | case3) # Remaining cases + + # Compute quaternions for case 1 + s1 = torch.sqrt(r_trace[case1] + 1.0) * 2 # S=4*qw + qw1 = 0.25 * s1 + qx1 = (rot[case1, 2, 1] - rot[case1, 1, 2]) / s1 + qy1 = (rot[case1, 0, 2] - rot[case1, 2, 0]) / s1 + qz1 = (rot[case1, 1, 0] - rot[case1, 0, 1]) / s1 + q[case1] = torch.stack([qw1, qx1, qy1, qz1], dim=-1) + + # Compute quaternions for case 2 + s2 = torch.sqrt(1.0 + rot[case2, 0, 0] - rot[case2, 1, 1] - rot[case2, 2, 2]) * 2 + qw2 = (rot[case2, 2, 1] - rot[case2, 1, 2]) / s2 + qx2 = 0.25 * s2 + qy2 = (rot[case2, 0, 1] + rot[case2, 1, 0]) / s2 + qz2 = (rot[case2, 0, 2] + rot[case2, 2, 0]) / s2 + q[case2] = torch.stack([qw2, qx2, qy2, qz2], dim=-1) + + # Compute quaternions for case 3 + s3 = torch.sqrt(1.0 + rot[case3, 1, 1] - rot[case3, 0, 0] - rot[case3, 2, 2]) * 2 + qw3 = (rot[case3, 0, 2] - rot[case3, 2, 0]) / s3 + qx3 = (rot[case3, 0, 1] + rot[case3, 1, 0]) / s3 + qy3 = 0.25 * s3 + qz3 = (rot[case3, 1, 2] + rot[case3, 2, 1]) / s3 + q[case3] = torch.stack([qw3, qx3, qy3, qz3], dim=-1) + + # Compute quaternions for case 4 + s4 = torch.sqrt(1.0 + rot[case4, 2, 2] - rot[case4, 0, 0] - rot[case4, 1, 1]) * 2 + qw4 = (rot[case4, 1, 0] - rot[case4, 0, 1]) / s4 + qx4 = (rot[case4, 0, 2] + rot[case4, 2, 0]) / s4 + qy4 = (rot[case4, 1, 2] + rot[case4, 2, 1]) / s4 + qz4 = 0.25 * s4 + q[case4] = torch.stack([qw4, qx4, qy4, qz4], dim=-1) + + q = q.view(orig_shape[:-2] + (4,)) + + return q \ No newline at end of file diff --git a/gafl/gafl/data/residue_constants.py b/gafl/gafl/data/residue_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..dd64043f5fdb649cf042cef10f5464e1cec57e22 --- /dev/null +++ b/gafl/gafl/data/residue_constants.py @@ -0,0 +1,898 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Constants used in AlphaFold.""" + +import collections +import functools +import os +from typing import List, Mapping, Tuple + +import numpy as np +import tree + +# Internal import (35fd). + + +# Distance from one CA to next CA [trans configuration: omega = 180]. +ca_ca = 3.80209737096 + +# Format: The list for each AA type contains chi1, chi2, chi3, chi4 in +# this order (or a relevant subset from chi1 onwards). ALA and GLY don't have +# chi angles so their chi angle lists are empty. +chi_angles_atoms = { + 'ALA': [], + # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. + 'ARG': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], + ['CB', 'CG', 'CD', 'NE'], ['CG', 'CD', 'NE', 'CZ']], + 'ASN': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'OD1']], + 'ASP': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'OD1']], + 'CYS': [['N', 'CA', 'CB', 'SG']], + 'GLN': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], + ['CB', 'CG', 'CD', 'OE1']], + 'GLU': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], + ['CB', 'CG', 'CD', 'OE1']], + 'GLY': [], + 'HIS': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'ND1']], + 'ILE': [['N', 'CA', 'CB', 'CG1'], ['CA', 'CB', 'CG1', 'CD1']], + 'LEU': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD1']], + 'LYS': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD'], + ['CB', 'CG', 'CD', 'CE'], ['CG', 'CD', 'CE', 'NZ']], + 'MET': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'SD'], + ['CB', 'CG', 'SD', 'CE']], + 'PHE': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD1']], + 'PRO': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD']], + 'SER': [['N', 'CA', 'CB', 'OG']], + 'THR': [['N', 'CA', 'CB', 'OG1']], + 'TRP': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD1']], + 'TYR': [['N', 'CA', 'CB', 'CG'], ['CA', 'CB', 'CG', 'CD1']], + 'VAL': [['N', 'CA', 'CB', 'CG1']], +} + +# If chi angles given in fixed-length array, this matrix determines how to mask +# them for each AA type. The order is as per restype_order (see below). +chi_angles_mask = [ + [0.0, 0.0, 0.0, 0.0], # ALA + [1.0, 1.0, 1.0, 1.0], # ARG + [1.0, 1.0, 0.0, 0.0], # ASN + [1.0, 1.0, 0.0, 0.0], # ASP + [1.0, 0.0, 0.0, 0.0], # CYS + [1.0, 1.0, 1.0, 0.0], # GLN + [1.0, 1.0, 1.0, 0.0], # GLU + [0.0, 0.0, 0.0, 0.0], # GLY + [1.0, 1.0, 0.0, 0.0], # HIS + [1.0, 1.0, 0.0, 0.0], # ILE + [1.0, 1.0, 0.0, 0.0], # LEU + [1.0, 1.0, 1.0, 1.0], # LYS + [1.0, 1.0, 1.0, 0.0], # MET + [1.0, 1.0, 0.0, 0.0], # PHE + [1.0, 1.0, 0.0, 0.0], # PRO + [1.0, 0.0, 0.0, 0.0], # SER + [1.0, 0.0, 0.0, 0.0], # THR + [1.0, 1.0, 0.0, 0.0], # TRP + [1.0, 1.0, 0.0, 0.0], # TYR + [1.0, 0.0, 0.0, 0.0], # VAL +] + +# The following chi angles are pi periodic: they can be rotated by a multiple +# of pi without affecting the structure. +chi_pi_periodic = [ + [0.0, 0.0, 0.0, 0.0], # ALA + [0.0, 0.0, 0.0, 0.0], # ARG + [0.0, 0.0, 0.0, 0.0], # ASN + [0.0, 1.0, 0.0, 0.0], # ASP + [0.0, 0.0, 0.0, 0.0], # CYS + [0.0, 0.0, 0.0, 0.0], # GLN + [0.0, 0.0, 1.0, 0.0], # GLU + [0.0, 0.0, 0.0, 0.0], # GLY + [0.0, 0.0, 0.0, 0.0], # HIS + [0.0, 0.0, 0.0, 0.0], # ILE + [0.0, 0.0, 0.0, 0.0], # LEU + [0.0, 0.0, 0.0, 0.0], # LYS + [0.0, 0.0, 0.0, 0.0], # MET + [0.0, 1.0, 0.0, 0.0], # PHE + [0.0, 0.0, 0.0, 0.0], # PRO + [0.0, 0.0, 0.0, 0.0], # SER + [0.0, 0.0, 0.0, 0.0], # THR + [0.0, 0.0, 0.0, 0.0], # TRP + [0.0, 1.0, 0.0, 0.0], # TYR + [0.0, 0.0, 0.0, 0.0], # VAL + [0.0, 0.0, 0.0, 0.0], # UNK +] + +# Atoms positions relative to the 8 rigid groups, defined by the pre-omega, phi, +# psi and chi angles: +# 0: 'backbone group', +# 1: 'pre-omega-group', (empty) +# 2: 'phi-group', (currently empty, because it defines only hydrogens) +# 3: 'psi-group', +# 4,5,6,7: 'chi1,2,3,4-group' +# The atom positions are relative to the axis-end-atom of the corresponding +# rotation axis. The x-axis is in direction of the rotation axis, and the y-axis +# is defined such that the dihedral-angle-definiting atom (the last entry in +# chi_angles_atoms above) is in the xy-plane (with a positive y-coordinate). +# format: [atomname, group_idx, rel_position] +rigid_group_atom_positions = { + 'ALA': [ + ['N', 0, (-0.525, 1.363, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, -0.000, -0.000)], + ['CB', 0, (-0.529, -0.774, -1.205)], + ['O', 3, (0.627, 1.062, 0.000)], + ], + 'ARG': [ + ['N', 0, (-0.524, 1.362, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, -0.000, -0.000)], + ['CB', 0, (-0.524, -0.778, -1.209)], + ['O', 3, (0.626, 1.062, 0.000)], + ['CG', 4, (0.616, 1.390, -0.000)], + ['CD', 5, (0.564, 1.414, 0.000)], + ['NE', 6, (0.539, 1.357, -0.000)], + ['NH1', 7, (0.206, 2.301, 0.000)], + ['NH2', 7, (2.078, 0.978, -0.000)], + ['CZ', 7, (0.758, 1.093, -0.000)], + ], + 'ASN': [ + ['N', 0, (-0.536, 1.357, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, -0.000, -0.000)], + ['CB', 0, (-0.531, -0.787, -1.200)], + ['O', 3, (0.625, 1.062, 0.000)], + ['CG', 4, (0.584, 1.399, 0.000)], + ['ND2', 5, (0.593, -1.188, 0.001)], + ['OD1', 5, (0.633, 1.059, 0.000)], + ], + 'ASP': [ + ['N', 0, (-0.525, 1.362, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.527, 0.000, -0.000)], + ['CB', 0, (-0.526, -0.778, -1.208)], + ['O', 3, (0.626, 1.062, -0.000)], + ['CG', 4, (0.593, 1.398, -0.000)], + ['OD1', 5, (0.610, 1.091, 0.000)], + ['OD2', 5, (0.592, -1.101, -0.003)], + ], + 'CYS': [ + ['N', 0, (-0.522, 1.362, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.524, 0.000, 0.000)], + ['CB', 0, (-0.519, -0.773, -1.212)], + ['O', 3, (0.625, 1.062, -0.000)], + ['SG', 4, (0.728, 1.653, 0.000)], + ], + 'GLN': [ + ['N', 0, (-0.526, 1.361, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, 0.000, 0.000)], + ['CB', 0, (-0.525, -0.779, -1.207)], + ['O', 3, (0.626, 1.062, -0.000)], + ['CG', 4, (0.615, 1.393, 0.000)], + ['CD', 5, (0.587, 1.399, -0.000)], + ['NE2', 6, (0.593, -1.189, -0.001)], + ['OE1', 6, (0.634, 1.060, 0.000)], + ], + 'GLU': [ + ['N', 0, (-0.528, 1.361, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, -0.000, -0.000)], + ['CB', 0, (-0.526, -0.781, -1.207)], + ['O', 3, (0.626, 1.062, 0.000)], + ['CG', 4, (0.615, 1.392, 0.000)], + ['CD', 5, (0.600, 1.397, 0.000)], + ['OE1', 6, (0.607, 1.095, -0.000)], + ['OE2', 6, (0.589, -1.104, -0.001)], + ], + 'GLY': [ + ['N', 0, (-0.572, 1.337, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.517, -0.000, -0.000)], + ['O', 3, (0.626, 1.062, -0.000)], + ], + 'HIS': [ + ['N', 0, (-0.527, 1.360, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, 0.000, 0.000)], + ['CB', 0, (-0.525, -0.778, -1.208)], + ['O', 3, (0.625, 1.063, 0.000)], + ['CG', 4, (0.600, 1.370, -0.000)], + ['CD2', 5, (0.889, -1.021, 0.003)], + ['ND1', 5, (0.744, 1.160, -0.000)], + ['CE1', 5, (2.030, 0.851, 0.002)], + ['NE2', 5, (2.145, -0.466, 0.004)], + ], + 'ILE': [ + ['N', 0, (-0.493, 1.373, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.527, -0.000, -0.000)], + ['CB', 0, (-0.536, -0.793, -1.213)], + ['O', 3, (0.627, 1.062, -0.000)], + ['CG1', 4, (0.534, 1.437, -0.000)], + ['CG2', 4, (0.540, -0.785, -1.199)], + ['CD1', 5, (0.619, 1.391, 0.000)], + ], + 'LEU': [ + ['N', 0, (-0.520, 1.363, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, -0.000, -0.000)], + ['CB', 0, (-0.522, -0.773, -1.214)], + ['O', 3, (0.625, 1.063, -0.000)], + ['CG', 4, (0.678, 1.371, 0.000)], + ['CD1', 5, (0.530, 1.430, -0.000)], + ['CD2', 5, (0.535, -0.774, 1.200)], + ], + 'LYS': [ + ['N', 0, (-0.526, 1.362, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, 0.000, 0.000)], + ['CB', 0, (-0.524, -0.778, -1.208)], + ['O', 3, (0.626, 1.062, -0.000)], + ['CG', 4, (0.619, 1.390, 0.000)], + ['CD', 5, (0.559, 1.417, 0.000)], + ['CE', 6, (0.560, 1.416, 0.000)], + ['NZ', 7, (0.554, 1.387, 0.000)], + ], + 'MET': [ + ['N', 0, (-0.521, 1.364, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, 0.000, 0.000)], + ['CB', 0, (-0.523, -0.776, -1.210)], + ['O', 3, (0.625, 1.062, -0.000)], + ['CG', 4, (0.613, 1.391, -0.000)], + ['SD', 5, (0.703, 1.695, 0.000)], + ['CE', 6, (0.320, 1.786, -0.000)], + ], + 'PHE': [ + ['N', 0, (-0.518, 1.363, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.524, 0.000, -0.000)], + ['CB', 0, (-0.525, -0.776, -1.212)], + ['O', 3, (0.626, 1.062, -0.000)], + ['CG', 4, (0.607, 1.377, 0.000)], + ['CD1', 5, (0.709, 1.195, -0.000)], + ['CD2', 5, (0.706, -1.196, 0.000)], + ['CE1', 5, (2.102, 1.198, -0.000)], + ['CE2', 5, (2.098, -1.201, -0.000)], + ['CZ', 5, (2.794, -0.003, -0.001)], + ], + 'PRO': [ + ['N', 0, (-0.566, 1.351, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.527, -0.000, 0.000)], + ['CB', 0, (-0.546, -0.611, -1.293)], + ['O', 3, (0.621, 1.066, 0.000)], + ['CG', 4, (0.382, 1.445, 0.0)], + # ['CD', 5, (0.427, 1.440, 0.0)], + ['CD', 5, (0.477, 1.424, 0.0)], # manually made angle 2 degrees larger + ], + 'SER': [ + ['N', 0, (-0.529, 1.360, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, -0.000, -0.000)], + ['CB', 0, (-0.518, -0.777, -1.211)], + ['O', 3, (0.626, 1.062, -0.000)], + ['OG', 4, (0.503, 1.325, 0.000)], + ], + 'THR': [ + ['N', 0, (-0.517, 1.364, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.526, 0.000, -0.000)], + ['CB', 0, (-0.516, -0.793, -1.215)], + ['O', 3, (0.626, 1.062, 0.000)], + ['CG2', 4, (0.550, -0.718, -1.228)], + ['OG1', 4, (0.472, 1.353, 0.000)], + ], + 'TRP': [ + ['N', 0, (-0.521, 1.363, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.525, -0.000, 0.000)], + ['CB', 0, (-0.523, -0.776, -1.212)], + ['O', 3, (0.627, 1.062, 0.000)], + ['CG', 4, (0.609, 1.370, -0.000)], + ['CD1', 5, (0.824, 1.091, 0.000)], + ['CD2', 5, (0.854, -1.148, -0.005)], + ['CE2', 5, (2.186, -0.678, -0.007)], + ['CE3', 5, (0.622, -2.530, -0.007)], + ['NE1', 5, (2.140, 0.690, -0.004)], + ['CH2', 5, (3.028, -2.890, -0.013)], + ['CZ2', 5, (3.283, -1.543, -0.011)], + ['CZ3', 5, (1.715, -3.389, -0.011)], + ], + 'TYR': [ + ['N', 0, (-0.522, 1.362, 0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.524, -0.000, -0.000)], + ['CB', 0, (-0.522, -0.776, -1.213)], + ['O', 3, (0.627, 1.062, -0.000)], + ['CG', 4, (0.607, 1.382, -0.000)], + ['CD1', 5, (0.716, 1.195, -0.000)], + ['CD2', 5, (0.713, -1.194, -0.001)], + ['CE1', 5, (2.107, 1.200, -0.002)], + ['CE2', 5, (2.104, -1.201, -0.003)], + ['OH', 5, (4.168, -0.002, -0.005)], + ['CZ', 5, (2.791, -0.001, -0.003)], + ], + 'VAL': [ + ['N', 0, (-0.494, 1.373, -0.000)], + ['CA', 0, (0.000, 0.000, 0.000)], + ['C', 0, (1.527, -0.000, -0.000)], + ['CB', 0, (-0.533, -0.795, -1.213)], + ['O', 3, (0.627, 1.062, -0.000)], + ['CG1', 4, (0.540, 1.429, -0.000)], + ['CG2', 4, (0.533, -0.776, 1.203)], + ], +} + +# A list of atoms (excluding hydrogen) for each AA type. PDB naming convention. +residue_atoms = { + 'ALA': ['C', 'CA', 'CB', 'N', 'O'], + 'ARG': ['C', 'CA', 'CB', 'CG', 'CD', 'CZ', 'N', 'NE', 'O', 'NH1', 'NH2'], + 'ASP': ['C', 'CA', 'CB', 'CG', 'N', 'O', 'OD1', 'OD2'], + 'ASN': ['C', 'CA', 'CB', 'CG', 'N', 'ND2', 'O', 'OD1'], + 'CYS': ['C', 'CA', 'CB', 'N', 'O', 'SG'], + 'GLU': ['C', 'CA', 'CB', 'CG', 'CD', 'N', 'O', 'OE1', 'OE2'], + 'GLN': ['C', 'CA', 'CB', 'CG', 'CD', 'N', 'NE2', 'O', 'OE1'], + 'GLY': ['C', 'CA', 'N', 'O'], + 'HIS': ['C', 'CA', 'CB', 'CG', 'CD2', 'CE1', 'N', 'ND1', 'NE2', 'O'], + 'ILE': ['C', 'CA', 'CB', 'CG1', 'CG2', 'CD1', 'N', 'O'], + 'LEU': ['C', 'CA', 'CB', 'CG', 'CD1', 'CD2', 'N', 'O'], + 'LYS': ['C', 'CA', 'CB', 'CG', 'CD', 'CE', 'N', 'NZ', 'O'], + 'MET': ['C', 'CA', 'CB', 'CG', 'CE', 'N', 'O', 'SD'], + 'PHE': ['C', 'CA', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2', 'CZ', 'N', 'O'], + 'PRO': ['C', 'CA', 'CB', 'CG', 'CD', 'N', 'O'], + 'SER': ['C', 'CA', 'CB', 'N', 'O', 'OG'], + 'THR': ['C', 'CA', 'CB', 'CG2', 'N', 'O', 'OG1'], + 'TRP': ['C', 'CA', 'CB', 'CG', 'CD1', 'CD2', 'CE2', 'CE3', 'CZ2', 'CZ3', + 'CH2', 'N', 'NE1', 'O'], + 'TYR': ['C', 'CA', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2', 'CZ', 'N', 'O', + 'OH'], + 'VAL': ['C', 'CA', 'CB', 'CG1', 'CG2', 'N', 'O'] +} + +# Naming swaps for ambiguous atom names. +# Due to symmetries in the amino acids the naming of atoms is ambiguous in +# 4 of the 20 amino acids. +# (The LDDT paper lists 7 amino acids as ambiguous, but the naming ambiguities +# in LEU, VAL and ARG can be resolved by using the 3d constellations of +# the 'ambiguous' atoms and their neighbours) +residue_atom_renaming_swaps = { + 'ASP': {'OD1': 'OD2'}, + 'GLU': {'OE1': 'OE2'}, + 'PHE': {'CD1': 'CD2', 'CE1': 'CE2'}, + 'TYR': {'CD1': 'CD2', 'CE1': 'CE2'}, +} + +# Van der Waals radii [Angstroem] of the atoms (from Wikipedia) +van_der_waals_radius = { + 'C': 1.7, + 'N': 1.55, + 'O': 1.52, + 'S': 1.8, +} + +Bond = collections.namedtuple( + 'Bond', ['atom1_name', 'atom2_name', 'length', 'stddev']) +BondAngle = collections.namedtuple( + 'BondAngle', + ['atom1_name', 'atom2_name', 'atom3name', 'angle_rad', 'stddev']) + + +@functools.lru_cache(maxsize=None) +def load_stereo_chemical_props() -> Tuple[Mapping[str, List[Bond]], + Mapping[str, List[Bond]], + Mapping[str, List[BondAngle]]]: + """Load stereo_chemical_props.txt into a nice structure. + + Load literature values for bond lengths and bond angles and translate + bond angles into the length of the opposite edge of the triangle + ("residue_virtual_bonds"). + + Returns: + residue_bonds: Dict that maps resname -> list of Bond tuples. + residue_virtual_bonds: Dict that maps resname -> list of Bond tuples. + residue_bond_angles: Dict that maps resname -> list of BondAngle tuples. + """ + stereo_chemical_props_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'stereo_chemical_props.txt' + ) + with open(stereo_chemical_props_path, 'rt') as f: + stereo_chemical_props = f.read() + lines_iter = iter(stereo_chemical_props.splitlines()) + # Load bond lengths. + residue_bonds = {} + next(lines_iter) # Skip header line. + for line in lines_iter: + if line.strip() == '-': + break + bond, resname, length, stddev = line.split() + atom1, atom2 = bond.split('-') + if resname not in residue_bonds: + residue_bonds[resname] = [] + residue_bonds[resname].append( + Bond(atom1, atom2, float(length), float(stddev))) + residue_bonds['UNK'] = [] + + # Load bond angles. + residue_bond_angles = {} + next(lines_iter) # Skip empty line. + next(lines_iter) # Skip header line. + for line in lines_iter: + if line.strip() == '-': + break + bond, resname, angle_degree, stddev_degree = line.split() + atom1, atom2, atom3 = bond.split('-') + if resname not in residue_bond_angles: + residue_bond_angles[resname] = [] + residue_bond_angles[resname].append( + BondAngle(atom1, atom2, atom3, + float(angle_degree) / 180. * np.pi, + float(stddev_degree) / 180. * np.pi)) + residue_bond_angles['UNK'] = [] + + def make_bond_key(atom1_name, atom2_name): + """Unique key to lookup bonds.""" + return '-'.join(sorted([atom1_name, atom2_name])) + + # Translate bond angles into distances ("virtual bonds"). + residue_virtual_bonds = {} + for resname, bond_angles in residue_bond_angles.items(): + # Create a fast lookup dict for bond lengths. + bond_cache = {} + for b in residue_bonds[resname]: + bond_cache[make_bond_key(b.atom1_name, b.atom2_name)] = b + residue_virtual_bonds[resname] = [] + for ba in bond_angles: + bond1 = bond_cache[make_bond_key(ba.atom1_name, ba.atom2_name)] + bond2 = bond_cache[make_bond_key(ba.atom2_name, ba.atom3name)] + + # Compute distance between atom1 and atom3 using the law of cosines + # c^2 = a^2 + b^2 - 2ab*cos(gamma). + gamma = ba.angle_rad + length = np.sqrt(bond1.length**2 + bond2.length**2 + - 2 * bond1.length * bond2.length * np.cos(gamma)) + + # Propagation of uncertainty assuming uncorrelated errors. + dl_outer = 0.5 / length + dl_dgamma = (2 * bond1.length * bond2.length * np.sin(gamma)) * dl_outer + dl_db1 = (2 * bond1.length - 2 * bond2.length * np.cos(gamma)) * dl_outer + dl_db2 = (2 * bond2.length - 2 * bond1.length * np.cos(gamma)) * dl_outer + stddev = np.sqrt((dl_dgamma * ba.stddev)**2 + + (dl_db1 * bond1.stddev)**2 + + (dl_db2 * bond2.stddev)**2) + residue_virtual_bonds[resname].append( + Bond(ba.atom1_name, ba.atom3name, length, stddev)) + + return (residue_bonds, + residue_virtual_bonds, + residue_bond_angles) + + +# Between-residue bond lengths for general bonds (first element) and for Proline +# (second element). +between_res_bond_length_c_n = [1.329, 1.341] +between_res_bond_length_stddev_c_n = [0.014, 0.016] + +# Between-residue cos_angles. +between_res_cos_angles_c_n_ca = [-0.5203, 0.0353] # degrees: 121.352 +- 2.315 +between_res_cos_angles_ca_c_n = [-0.4473, 0.0311] # degrees: 116.568 +- 1.995 + +# This mapping is used when we need to store atom data in a format that requires +# fixed atom data size for every residue (e.g. a numpy array). +atom_types = [ + 'N', 'CA', 'C', 'CB', 'O', 'CG', 'CG1', 'CG2', 'OG', 'OG1', 'SG', 'CD', + 'CD1', 'CD2', 'ND1', 'ND2', 'OD1', 'OD2', 'SD', 'CE', 'CE1', 'CE2', 'CE3', + 'NE', 'NE1', 'NE2', 'OE1', 'OE2', 'CH2', 'NH1', 'NH2', 'OH', 'CZ', 'CZ2', + 'CZ3', 'NZ', 'OXT' +] +atom_order = {atom_type: i for i, atom_type in enumerate(atom_types)} +atom_type_num = len(atom_types) # := 37. + +# A compact atom encoding with 14 columns +# pylint: disable=line-too-long +# pylint: disable=bad-whitespace +restype_name_to_atom14_names = { + 'ALA': ['N', 'CA', 'C', 'O', 'CB', '', '', '', '', '', '', '', '', ''], + 'ARG': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'NE', 'CZ', 'NH1', 'NH2', '', '', ''], + 'ASN': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'OD1', 'ND2', '', '', '', '', '', ''], + 'ASP': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'OD1', 'OD2', '', '', '', '', '', ''], + 'CYS': ['N', 'CA', 'C', 'O', 'CB', 'SG', '', '', '', '', '', '', '', ''], + 'GLN': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'OE1', 'NE2', '', '', '', '', ''], + 'GLU': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'OE1', 'OE2', '', '', '', '', ''], + 'GLY': ['N', 'CA', 'C', 'O', '', '', '', '', '', '', '', '', '', ''], + 'HIS': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'ND1', 'CD2', 'CE1', 'NE2', '', '', '', ''], + 'ILE': ['N', 'CA', 'C', 'O', 'CB', 'CG1', 'CG2', 'CD1', '', '', '', '', '', ''], + 'LEU': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', '', '', '', '', '', ''], + 'LYS': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', 'CE', 'NZ', '', '', '', '', ''], + 'MET': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'SD', 'CE', '', '', '', '', '', ''], + 'PHE': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2', 'CZ', '', '', ''], + 'PRO': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD', '', '', '', '', '', '', ''], + 'SER': ['N', 'CA', 'C', 'O', 'CB', 'OG', '', '', '', '', '', '', '', ''], + 'THR': ['N', 'CA', 'C', 'O', 'CB', 'OG1', 'CG2', '', '', '', '', '', '', ''], + 'TRP': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'NE1', 'CE2', 'CE3', 'CZ2', 'CZ3', 'CH2'], + 'TYR': ['N', 'CA', 'C', 'O', 'CB', 'CG', 'CD1', 'CD2', 'CE1', 'CE2', 'CZ', 'OH', '', ''], + 'VAL': ['N', 'CA', 'C', 'O', 'CB', 'CG1', 'CG2', '', '', '', '', '', '', ''], + 'UNK': ['', '', '', '', '', '', '', '', '', '', '', '', '', ''], + +} +# pylint: enable=line-too-long +# pylint: enable=bad-whitespace + + +# This is the standard residue order when coding AA type as a number. +# Reproduce it by taking 3-letter AA codes and sorting them alphabetically. +restypes = [ + 'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', + 'S', 'T', 'W', 'Y', 'V' +] +restype_order = {restype: i for i, restype in enumerate(restypes)} +restype_num = len(restypes) # := 20. +unk_restype_index = restype_num # Catch-all index for unknown restypes. + +restypes_with_x = restypes + ['X'] +restype_order_with_x = {restype: i for i, restype in enumerate(restypes_with_x)} + + +def sequence_to_onehot( + sequence: str, + mapping: Mapping[str, int], + map_unknown_to_x: bool = False) -> np.ndarray: + """Maps the given sequence into a one-hot encoded matrix. + + Args: + sequence: An amino acid sequence. + mapping: A dictionary mapping amino acids to integers. + map_unknown_to_x: If True, any amino acid that is not in the mapping will be + mapped to the unknown amino acid 'X'. If the mapping doesn't contain + amino acid 'X', an error will be thrown. If False, any amino acid not in + the mapping will throw an error. + + Returns: + A numpy array of shape (seq_len, num_unique_aas) with one-hot encoding of + the sequence. + + Raises: + ValueError: If the mapping doesn't contain values from 0 to + num_unique_aas - 1 without any gaps. + """ + num_entries = max(mapping.values()) + 1 + + if sorted(set(mapping.values())) != list(range(num_entries)): + raise ValueError('The mapping must have values from 0 to num_unique_aas-1 ' + 'without any gaps. Got: %s' % sorted(mapping.values())) + + one_hot_arr = np.zeros((len(sequence), num_entries), dtype=int) + + for aa_index, aa_type in enumerate(sequence): + if map_unknown_to_x: + if aa_type.isalpha() and aa_type.isupper(): + aa_id = mapping.get(aa_type, mapping['X']) + else: + raise ValueError(f'Invalid character in the sequence: {aa_type}') + else: + aa_id = mapping[aa_type] + one_hot_arr[aa_index, aa_id] = 1 + + return one_hot_arr + + +restype_1to3 = { + 'A': 'ALA', + 'R': 'ARG', + 'N': 'ASN', + 'D': 'ASP', + 'C': 'CYS', + 'Q': 'GLN', + 'E': 'GLU', + 'G': 'GLY', + 'H': 'HIS', + 'I': 'ILE', + 'L': 'LEU', + 'K': 'LYS', + 'M': 'MET', + 'F': 'PHE', + 'P': 'PRO', + 'S': 'SER', + 'T': 'THR', + 'W': 'TRP', + 'Y': 'TYR', + 'V': 'VAL', +} + + +# NB: restype_3to1 differs from Bio.PDB.protein_letters_3to1 by being a simple +# 1-to-1 mapping of 3 letter names to one letter names. The latter contains +# many more, and less common, three letter names as keys and maps many of these +# to the same one letter name (including 'X' and 'U' which we don't use here). +restype_3to1 = {v: k for k, v in restype_1to3.items()} + +# Define a restype name for all unknown residues. +unk_restype = 'UNK' + +resnames = [restype_1to3[r] for r in restypes] + [unk_restype] +resname_to_idx = {resname: i for i, resname in enumerate(resnames)} + + +# The mapping here uses hhblits convention, so that B is mapped to D, J and O +# are mapped to X, U is mapped to C, and Z is mapped to E. Other than that the +# remaining 20 amino acids are kept in alphabetical order. +# There are 2 non-amino acid codes, X (representing any amino acid) and +# "-" representing a missing amino acid in an alignment. The id for these +# codes is put at the end (20 and 21) so that they can easily be ignored if +# desired. +HHBLITS_AA_TO_ID = { + 'A': 0, + 'B': 2, + 'C': 1, + 'D': 2, + 'E': 3, + 'F': 4, + 'G': 5, + 'H': 6, + 'I': 7, + 'J': 20, + 'K': 8, + 'L': 9, + 'M': 10, + 'N': 11, + 'O': 20, + 'P': 12, + 'Q': 13, + 'R': 14, + 'S': 15, + 'T': 16, + 'U': 1, + 'V': 17, + 'W': 18, + 'X': 20, + 'Y': 19, + 'Z': 3, + '-': 21, +} + +# Partial inversion of HHBLITS_AA_TO_ID. +ID_TO_HHBLITS_AA = { + 0: 'A', + 1: 'C', # Also U. + 2: 'D', # Also B. + 3: 'E', # Also Z. + 4: 'F', + 5: 'G', + 6: 'H', + 7: 'I', + 8: 'K', + 9: 'L', + 10: 'M', + 11: 'N', + 12: 'P', + 13: 'Q', + 14: 'R', + 15: 'S', + 16: 'T', + 17: 'V', + 18: 'W', + 19: 'Y', + 20: 'X', # Includes J and O. + 21: '-', +} + +restypes_with_x_and_gap = restypes + ['X', '-'] +MAP_HHBLITS_AATYPE_TO_OUR_AATYPE = tuple( + restypes_with_x_and_gap.index(ID_TO_HHBLITS_AA[i]) + for i in range(len(restypes_with_x_and_gap))) + + +def _make_standard_atom_mask() -> np.ndarray: + """Returns [num_res_types, num_atom_types] mask array.""" + # +1 to account for unknown (all 0s). + mask = np.zeros([restype_num + 1, atom_type_num], dtype=int) + for restype, restype_letter in enumerate(restypes): + restype_name = restype_1to3[restype_letter] + atom_names = residue_atoms[restype_name] + for atom_name in atom_names: + atom_type = atom_order[atom_name] + mask[restype, atom_type] = 1 + return mask + + +STANDARD_ATOM_MASK = _make_standard_atom_mask() + + +# A one hot representation for the first and second atoms defining the axis +# of rotation for each chi-angle in each residue. +def chi_angle_atom(atom_index: int) -> np.ndarray: + """Define chi-angle rigid groups via one-hot representations.""" + chi_angles_index = {} + one_hots = [] + + for k, v in chi_angles_atoms.items(): + indices = [atom_types.index(s[atom_index]) for s in v] + indices.extend([-1]*(4-len(indices))) + chi_angles_index[k] = indices + + for r in restypes: + res3 = restype_1to3[r] + one_hot = np.eye(atom_type_num)[chi_angles_index[res3]] + one_hots.append(one_hot) + + one_hots.append(np.zeros([4, atom_type_num])) # Add zeros for residue `X`. + one_hot = np.stack(one_hots, axis=0) + one_hot = np.transpose(one_hot, [0, 2, 1]) + + return one_hot + +chi_atom_1_one_hot = chi_angle_atom(1) +chi_atom_2_one_hot = chi_angle_atom(2) + +# An array like chi_angles_atoms but using indices rather than names. +chi_angles_atom_indices = [chi_angles_atoms[restype_1to3[r]] for r in restypes] +chi_angles_atom_indices = tree.map_structure( + lambda atom_name: atom_order[atom_name], chi_angles_atom_indices) +chi_angles_atom_indices = np.array([ + chi_atoms + ([[0, 0, 0, 0]] * (4 - len(chi_atoms))) + for chi_atoms in chi_angles_atom_indices]) + +# Mapping from (res_name, atom_name) pairs to the atom's chi group index +# and atom index within that group. +chi_groups_for_atom = collections.defaultdict(list) +for res_name, chi_angle_atoms_for_res in chi_angles_atoms.items(): + for chi_group_i, chi_group in enumerate(chi_angle_atoms_for_res): + for atom_i, atom in enumerate(chi_group): + chi_groups_for_atom[(res_name, atom)].append((chi_group_i, atom_i)) +chi_groups_for_atom = dict(chi_groups_for_atom) + + +def _make_rigid_transformation_4x4(ex, ey, translation): + """Create a rigid 4x4 transformation matrix from two axes and transl.""" + # Normalize ex. + ex_normalized = ex / np.linalg.norm(ex) + + # make ey perpendicular to ex + ey_normalized = ey - np.dot(ey, ex_normalized) * ex_normalized + ey_normalized /= np.linalg.norm(ey_normalized) + + # compute ez as cross product + eznorm = np.cross(ex_normalized, ey_normalized) + m = np.stack([ex_normalized, ey_normalized, eznorm, translation]).transpose() + m = np.concatenate([m, [[0., 0., 0., 1.]]], axis=0) + return m + + +# create an array with (restype, atomtype) --> rigid_group_idx +# and an array with (restype, atomtype, coord) for the atom positions +# and compute affine transformation matrices (4,4) from one rigid group to the +# previous group +restype_atom37_to_rigid_group = np.zeros([21, 37], dtype=int) +restype_atom37_mask = np.zeros([21, 37], dtype=np.float32) +restype_atom37_rigid_group_positions = np.zeros([21, 37, 3], dtype=np.float32) +restype_atom14_to_rigid_group = np.zeros([21, 14], dtype=int) +restype_atom14_mask = np.zeros([21, 14], dtype=np.float32) +restype_atom14_rigid_group_positions = np.zeros([21, 14, 3], dtype=np.float32) +restype_rigid_group_default_frame = np.zeros([21, 8, 4, 4], dtype=np.float32) + + +def _make_rigid_group_constants(): + """Fill the arrays above.""" + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + for atomname, group_idx, atom_position in rigid_group_atom_positions[ + resname]: + atomtype = atom_order[atomname] + restype_atom37_to_rigid_group[restype, atomtype] = group_idx + restype_atom37_mask[restype, atomtype] = 1 + restype_atom37_rigid_group_positions[restype, atomtype, :] = atom_position + + atom14idx = restype_name_to_atom14_names[resname].index(atomname) + restype_atom14_to_rigid_group[restype, atom14idx] = group_idx + restype_atom14_mask[restype, atom14idx] = 1 + restype_atom14_rigid_group_positions[restype, + atom14idx, :] = atom_position + + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + atom_positions = {name: np.array(pos) for name, _, pos + in rigid_group_atom_positions[resname]} + + # backbone to backbone is the identity transform + restype_rigid_group_default_frame[restype, 0, :, :] = np.eye(4) + + # pre-omega-frame to backbone (currently dummy identity matrix) + restype_rigid_group_default_frame[restype, 1, :, :] = np.eye(4) + + # phi-frame to backbone + mat = _make_rigid_transformation_4x4( + ex=atom_positions['N'] - atom_positions['CA'], + ey=np.array([1., 0., 0.]), + translation=atom_positions['N']) + restype_rigid_group_default_frame[restype, 2, :, :] = mat + + # psi-frame to backbone + mat = _make_rigid_transformation_4x4( + ex=atom_positions['C'] - atom_positions['CA'], + ey=atom_positions['CA'] - atom_positions['N'], + translation=atom_positions['C']) + restype_rigid_group_default_frame[restype, 3, :, :] = mat + + # chi1-frame to backbone + if chi_angles_mask[restype][0]: + base_atom_names = chi_angles_atoms[resname][0] + base_atom_positions = [atom_positions[name] for name in base_atom_names] + mat = _make_rigid_transformation_4x4( + ex=base_atom_positions[2] - base_atom_positions[1], + ey=base_atom_positions[0] - base_atom_positions[1], + translation=base_atom_positions[2]) + restype_rigid_group_default_frame[restype, 4, :, :] = mat + + # chi2-frame to chi1-frame + # chi3-frame to chi2-frame + # chi4-frame to chi3-frame + # luckily all rotation axes for the next frame start at (0,0,0) of the + # previous frame + for chi_idx in range(1, 4): + if chi_angles_mask[restype][chi_idx]: + axis_end_atom_name = chi_angles_atoms[resname][chi_idx][2] + axis_end_atom_position = atom_positions[axis_end_atom_name] + mat = _make_rigid_transformation_4x4( + ex=axis_end_atom_position, + ey=np.array([-1., 0., 0.]), + translation=axis_end_atom_position) + restype_rigid_group_default_frame[restype, 4 + chi_idx, :, :] = mat + + +_make_rigid_group_constants() + + +def make_atom14_dists_bounds(overlap_tolerance=1.5, + bond_length_tolerance_factor=15): + """compute upper and lower bounds for bonds to assess violations.""" + restype_atom14_bond_lower_bound = np.zeros([21, 14, 14], np.float32) + restype_atom14_bond_upper_bound = np.zeros([21, 14, 14], np.float32) + restype_atom14_bond_stddev = np.zeros([21, 14, 14], np.float32) + residue_bonds, residue_virtual_bonds, _ = load_stereo_chemical_props() + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + atom_list = restype_name_to_atom14_names[resname] + + # create lower and upper bounds for clashes + for atom1_idx, atom1_name in enumerate(atom_list): + if not atom1_name: + continue + atom1_radius = van_der_waals_radius[atom1_name[0]] + for atom2_idx, atom2_name in enumerate(atom_list): + if (not atom2_name) or atom1_idx == atom2_idx: + continue + atom2_radius = van_der_waals_radius[atom2_name[0]] + lower = atom1_radius + atom2_radius - overlap_tolerance + upper = 1e10 + restype_atom14_bond_lower_bound[restype, atom1_idx, atom2_idx] = lower + restype_atom14_bond_lower_bound[restype, atom2_idx, atom1_idx] = lower + restype_atom14_bond_upper_bound[restype, atom1_idx, atom2_idx] = upper + restype_atom14_bond_upper_bound[restype, atom2_idx, atom1_idx] = upper + + # overwrite lower and upper bounds for bonds and angles + for b in residue_bonds[resname] + residue_virtual_bonds[resname]: + atom1_idx = atom_list.index(b.atom1_name) + atom2_idx = atom_list.index(b.atom2_name) + lower = b.length - bond_length_tolerance_factor * b.stddev + upper = b.length + bond_length_tolerance_factor * b.stddev + restype_atom14_bond_lower_bound[restype, atom1_idx, atom2_idx] = lower + restype_atom14_bond_lower_bound[restype, atom2_idx, atom1_idx] = lower + restype_atom14_bond_upper_bound[restype, atom1_idx, atom2_idx] = upper + restype_atom14_bond_upper_bound[restype, atom2_idx, atom1_idx] = upper + restype_atom14_bond_stddev[restype, atom1_idx, atom2_idx] = b.stddev + restype_atom14_bond_stddev[restype, atom2_idx, atom1_idx] = b.stddev + return {'lower_bound': restype_atom14_bond_lower_bound, # shape (21,14,14) + 'upper_bound': restype_atom14_bond_upper_bound, # shape (21,14,14) + 'stddev': restype_atom14_bond_stddev, # shape (21,14,14) + } \ No newline at end of file diff --git a/gafl/gafl/data/so3_utils.py b/gafl/gafl/data/so3_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8f92875988c6f245868c9f0894bcabcf824303 --- /dev/null +++ b/gafl/gafl/data/so3_utils.py @@ -0,0 +1,1473 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import logging +import os +from typing import Callable, Dict, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from tqdm import tqdm + +logger = logging.getLogger(__name__) + + +def scale_rotmat( + rotation_matrix: torch.Tensor, scalar: torch.Tensor, tol: float = 1e-7 +) -> torch.Tensor: + """ + Scale rotation matrix. This is done by converting it to vector representation, + scaling the length of the vector and converting back to matrix representation. + + Args: + rotation_matrix: Rotation matrices. + scalar: Scalar values used for scaling. Should have one fewer dimension than the + rotation matrices for correct broadcasting. + tol: Numerical offset for stability. + + Returns: + Scaled rotation matrix. + """ + # Check whether dimensions match. + assert rotation_matrix.ndim - 1 == scalar.ndim + scaled_rmat = rotvec_to_rotmat(rotmat_to_rotvec(rotation_matrix) * scalar, tol=tol) + return scaled_rmat + + +def _broadcast_identity(target: torch.Tensor) -> torch.Tensor: + """ + Generate a 3 by 3 identity matrix and broadcast it to a batch of target matrices. + + Args: + target (torch.Tensor): Batch of target 3 by 3 matrices. + + Returns: + torch.Tensor: 3 by 3 identity matrices in the shapes of the target. + """ + id3 = torch.eye(3, device=target.device, dtype=target.dtype) + id3 = torch.broadcast_to(id3, target.shape) + return id3 + + +def skew_matrix_exponential_map_axis_angle( + angles: torch.Tensor, skew_matrices: torch.Tensor +) -> torch.Tensor: + r""" + Compute the matrix exponential of a rotation in axis-angle representation with the axis in skew + matrix representation form. Maps the rotation from the lie group to the rotation matrix + representation. Uses Rodrigues' formula instead of `torch.linalg.matrix_exp` for better + computational performance: + + .. math:: + + \exp(\theta \mathbf{K}) = \mathbf{I} + \sin(\theta) \mathbf{K} + [1 - \cos(\theta)] \mathbf{K}^2 + + Args: + angles (torch.Tensor): Batch of rotation angles. + skew_matrices (torch.Tensor): Batch of rotation axes in skew matrix (lie so(3)) basis. + + Returns: + torch.Tensor: Batch of corresponding rotation matrices. + """ + # Set up identity matrix and broadcast. + id3 = _broadcast_identity(skew_matrices) + + # Broadcast angle vector to right dimensions + angles = angles[..., None, None] + + exp_skew = ( + id3 + + torch.sin(angles) * skew_matrices + + (1.0 - torch.cos(angles)) + * torch.einsum("b...ik,b...kj->b...ij", skew_matrices, skew_matrices) + ) + return exp_skew + + +def skew_matrix_exponential_map( + angles: torch.Tensor, skew_matrices: torch.Tensor, tol=1e-7 +) -> torch.Tensor: + r""" + Compute the matrix exponential of a rotation vector in skew matrix representation. Maps the + rotation from the lie group to the rotation matrix representation. Uses the following form of + Rodrigues' formula instead of `torch.linalg.matrix_exp` for better computational performance + (in this case the skew matrix already contains the angle factor): + + .. math:: + + \exp(\mathbf{K}) = \mathbf{I} + \frac{\sin(\theta)}{\theta} \mathbf{K} + \frac{1-\cos(\theta)}{\theta^2} \mathbf{K}^2 + + This form has the advantage, that Taylor expansions can be used for small angles (instead of + having to compute the unit length axis by dividing the rotation vector by small angles): + + .. math:: + + \frac{\sin(\theta)}{\theta} \approx 1 - \frac{\theta^2}{6} + \frac{1-\cos(\theta)}{\theta^2} \approx \frac{1}{2} - \frac{\theta^2}{24} + + Args: + angles (torch.Tensor): Batch of rotation angles. + skew_matrices (torch.Tensor): Batch of rotation axes in skew matrix (lie so(3)) basis. + + Returns: + torch.Tensor: Batch of corresponding rotation matrices. + """ + # Set up identity matrix and broadcast. + id3 = _broadcast_identity(skew_matrices) + + # Broadcast angles and pre-compute square. + angles = angles[..., None, None] + angles_sq = angles.square() + + # Get standard terms. + sin_coeff = torch.sin(angles) / angles + cos_coeff = (1.0 - torch.cos(angles)) / angles_sq + # Use second order Taylor expansion for values close to zero. + sin_coeff_small = 1.0 - angles_sq / 6.0 + cos_coeff_small = 0.5 - angles_sq / 24.0 + + mask_zero = torch.abs(angles) < tol + sin_coeff = torch.where(mask_zero, sin_coeff_small, sin_coeff) + cos_coeff = torch.where(mask_zero, cos_coeff_small, cos_coeff) + + # Compute matrix exponential using Rodrigues' formula. + exp_skew = ( + id3 + + sin_coeff * skew_matrices + + cos_coeff * torch.einsum("b...ik,b...kj->b...ij", skew_matrices, skew_matrices) + ) + return exp_skew + + +def rotvec_to_rotmat(rotation_vectors: torch.Tensor, tol: float = 1e-7) -> torch.Tensor: + """ + Convert rotation vectors to rotation matrix representation. The length of the rotation vector + is the angle of rotation, the unit vector the rotation axis. + + Args: + rotation_vectors (torch.Tensor): Batch of rotation vectors. + tol: small offset for numerical stability. + + Returns: + torch.Tensor: Rotation in rotation matrix representation. + """ + # Compute rotation angle as vector norm. + rotation_angles = torch.norm(rotation_vectors, dim=-1) + + # Map axis to skew matrix basis. + skew_matrices = vector_to_skew_matrix(rotation_vectors) + + # Compute rotation matrices via matrix exponential. + rotation_matrices = skew_matrix_exponential_map(rotation_angles, skew_matrices, tol=tol) + + return rotation_matrices + + +def rotmat_to_rotvec(rotation_matrices: torch.Tensor) -> torch.Tensor: + r""" + Convert a batch of rotation matrices to rotation vectors (logarithmic map from SO(3) to so(3)). + The standard logarithmic map can be derived from Rodrigues' formula via Taylor approximation + (in this case operating on the vector coefficients of the skew so(3) basis). + + .. math:: + + \left[\log(\mathbf{R})\right]^\lor = \frac{\theta}{2\sin(\theta)} \left[\mathbf{R} - \mathbf{R}^\top\right]^\lor + + This formula has problems at 1) angles theta close or equal to zero and 2) at angles close and + equal to pi. + + To improve numerical stability for case 1), the angle term at small or zero angles is + approximated by its truncated Taylor expansion: + + .. math:: + + \left[\log(\mathbf{R})\right]^\lor \approx \frac{1}{2} (1 + \frac{\theta^2}{6}) \left[\mathbf{R} - \mathbf{R}^\top\right]^\lor + + For angles close or equal to pi (case 2), the outer product relation can be used to obtain the + squared rotation vector: + + .. math:: \omega \otimes \omega = \frac{1}{2}(\mathbf{I} + R) + + Taking the root of the diagonal elements recovers the normalized rotation vector up to the signs + of the component. The latter can be obtained from the off-diagonal elements. + + Adapted from https://github.com/jasonkyuyim/se3_diffusion/blob/2cba9e09fdc58112126a0441493b42022c62bbea/data/so3_utils.py + which was adapted from https://github.com/geomstats/geomstats/blob/master/geomstats/geometry/special_orthogonal.py + with heavy help from https://cvg.cit.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf + + Args: + rotation_matrices (torch.Tensor): Input batch of rotation matrices. + + Returns: + torch.Tensor: Batch of rotation vectors. + """ + # Get angles and sin/cos from rotation matrix. + angles, angles_sin, _ = angle_from_rotmat(rotation_matrices) + # Compute skew matrix representation and extract so(3) vector components. + vector = skew_matrix_to_vector(rotation_matrices - rotation_matrices.transpose(-2, -1)) + + # Three main cases for angle theta, which are captured + # 1) Angle is 0 or close to zero -> use Taylor series for small values / return 0 vector. + mask_zero = torch.isclose(angles, torch.zeros_like(angles)).to(angles.dtype) + # 2) Angle is close to pi -> use outer product relation. + mask_pi = torch.isclose(angles, torch.full_like(angles, np.pi), atol=1e-2).to(angles.dtype) + # 3) Angle is unproblematic -> use the standard formula. + mask_else = (1 - mask_zero) * (1 - mask_pi) + + # Compute case dependent pre-factor (1/2 for angle close to 0, angle otherwise). + numerator = mask_zero / 2.0 + angles * mask_else + # The Taylor expansion used here is actually the inverse of the Taylor expansion of the inverted + # fraction sin(x) / x which gives better accuracy over a wider range (hence the minus and + # position in denominator). + denominator = ( + (1.0 - angles**2 / 6.0) * mask_zero # Taylor expansion for small angles. + + 2.0 * angles_sin * mask_else # Standard formula. + + mask_pi # Avoid zero division at angle == pi. + ) + prefactor = numerator / denominator + vector = vector * prefactor[..., None] + + # For angles close to pi, derive vectors from their outer product (ww' = 1 + R). + id3 = _broadcast_identity(rotation_matrices) + skew_outer = (id3 + rotation_matrices) / 2.0 + # Ensure diagonal is >= 0 for square root (uses identity for masking). + skew_outer = skew_outer + (torch.relu(skew_outer) - skew_outer) * id3 + + # Get basic rotation vector as sqrt of diagonal (is unit vector). + vector_pi = torch.sqrt(torch.diagonal(skew_outer, dim1=-2, dim2=-1)) + + # Compute the signs of vector elements (up to a global phase). + # Fist select indices for outer product slices with the largest norm. + signs_line_idx = torch.argmax(torch.norm(skew_outer, dim=-1), dim=-1).long() + # Select rows of outer product and determine signs. + signs_line = torch.take_along_dim(skew_outer, dim=-2, indices=signs_line_idx[..., None, None]) + signs_line = signs_line.squeeze(-2) + signs = torch.sign(signs_line) + + # Apply signs and rotation vector. + vector_pi = vector_pi * angles[..., None] * signs + + # Fill entries for angle == pi in rotation vector (basic vector has zero entries at this point). + vector = vector + vector_pi * mask_pi[..., None] + + return vector + + +def angle_from_rotmat( + rotation_matrices: torch.Tensor, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Compute rotation angles (as well as their sines and cosines) encoded by rotation matrices. + Uses atan2 for better numerical stability for small angles. + + Args: + rotation_matrices (torch.Tensor): Batch of rotation matrices. + + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Batch of computed angles, sines of the + angles and cosines of angles. + """ + # Compute sine of angles (uses the relation that the unnormalized skew vector generated by a + # rotation matrix has the length 2*sin(theta)) + skew_matrices = rotation_matrices - rotation_matrices.transpose(-2, -1) + skew_vectors = skew_matrix_to_vector(skew_matrices) + angles_sin = torch.norm(skew_vectors, dim=-1) / 2.0 + # Compute the cosine of the angle using the relation cos theta = 1/2 * (Tr[R] - 1) + angles_cos = (torch.einsum("...ii", rotation_matrices) - 1.0) / 2.0 + + # Compute angles using the more stable atan2 + angles = torch.atan2(angles_sin, angles_cos) + + return angles, angles_sin, angles_cos + + +def vector_to_skew_matrix(vectors: torch.Tensor) -> torch.Tensor: + """ + Map a vector into the corresponding skew matrix so(3) basis. + ``` + [ 0 -z y] + [x,y,z] -> [ z 0 -x] + [ -y x 0] + ``` + + Args: + vectors (torch.Tensor): Batch of vectors to be mapped to skew matrices. + + Returns: + torch.Tensor: Vectors in skew matrix representation. + """ + # Generate empty skew matrices. + skew_matrices = torch.zeros((*vectors.shape, 3), device=vectors.device, dtype=vectors.dtype) + + # Populate positive values. + skew_matrices[..., 2, 1] = vectors[..., 0] + skew_matrices[..., 0, 2] = vectors[..., 1] + skew_matrices[..., 1, 0] = vectors[..., 2] + + # Generate skew symmetry. + skew_matrices = skew_matrices - skew_matrices.transpose(-2, -1) + + return skew_matrices + + +def skew_matrix_to_vector(skew_matrices: torch.Tensor) -> torch.Tensor: + """ + Extract a rotation vector from the so(3) skew matrix basis. + + Args: + skew_matrices (torch.Tensor): Skew matrices. + + Returns: + torch.Tensor: Rotation vectors corresponding to skew matrices. + """ + vectors = torch.zeros_like(skew_matrices[..., 0]) + vectors[..., 0] = skew_matrices[..., 2, 1] + vectors[..., 1] = skew_matrices[..., 0, 2] + vectors[..., 2] = skew_matrices[..., 1, 0] + return vectors + + +def _rotquat_to_axis_angle( + rotation_quaternions: torch.Tensor, tol: float = 1e-7 +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Auxiliary routine for computing rotation angle and rotation axis from unit quaternions. To avoid + complications, rotations vectors with angles below `tol` are set to zero. + + Args: + rotation_quaternions (torch.Tensor): Rotation quaternions in [r, i, j, k] format. + tol (float, optional): Threshold for small rotations. Defaults to 1e-7. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Rotation angles and axes. + """ + # Compute rotation axis and normalize (accounting for small length axes). + rotation_axes = rotation_quaternions[..., 1:] + rotation_axes_norms = torch.norm(rotation_axes, dim=-1) + + # Compute rotation angle via atan2 + rotation_angles = 2.0 * torch.atan2(rotation_axes_norms, rotation_quaternions[..., 0]) + + # Save division. + rotation_axes = rotation_axes / (rotation_axes_norms[..., None] + tol) # Changed rotation_axes_norms[:, None] -> rotation_axes_norms[..., None] + return rotation_angles, rotation_axes + + +def rotquat_to_rotvec(rotation_quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert unit quaternions to rotation vectors. + + Args: + rotation_quaternions (torch.Tensor): Input quaternions in [r,i,j,k] format. + + Returns: + torch.Tensor: Rotation vectors. + """ + rotation_angles, rotation_axes = _rotquat_to_axis_angle(rotation_quaternions) + rotation_vectors = rotation_axes * rotation_angles[..., None] + return rotation_vectors + + +def rotquat_to_rotmat(rotation_quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert unit quaternion to rotation matrix. + + Args: + rotation_quaternions (torch.Tensor): Input quaternions in [r,i,j,k] format. + + Returns: + torch.Tensor: Rotation matrices. + """ + rotation_angles, rotation_axes = _rotquat_to_axis_angle(rotation_quaternions) + skew_matrices = vector_to_skew_matrix(rotation_axes * rotation_angles[..., None]) + rotation_matrices = skew_matrix_exponential_map(rotation_angles, skew_matrices) + return rotation_matrices + + +############################################################################################ +# The following code is copied from the pytorch3d and not from the original repo +############################################################################################ + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + ret[positive_mask] = torch.sqrt(x[positive_mask]) + return ret + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part first, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 0:1] < 0, -quaternions, quaternions) + +def rotmat_to_rotquat(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part first, as tensor of shape (..., 4). + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind( + matrix.reshape(batch_dim + (9,)), dim=-1 + ) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + # we produce the desired quaternion multiplied by each of r, i, j, k + quat_by_rijk = torch.stack( + [ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + # We floor here at 0.1 but the exact level is not important; if q_abs is small, + # the candidate won't be picked. + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + # if not for numerical problems, quat_candidates[i] should be same (up to a sign), + # forall i; we pick the best-conditioned one (with the largest denominator) + out = quat_candidates[ + F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, : + ].reshape(batch_dim + (4,)) + return standardize_quaternion(out) + +############################################################################################ +# # +############################################################################################ + +def apply_rotvec_to_rotmat( + rotation_matrices: torch.Tensor, + rotation_vectors: torch.Tensor, + tol: float = 1e-7, +) -> torch.Tensor: + """ + Update a rotation encoded in a rotation matrix with a rotation vector. + + Args: + rotation_matrices: Input batch of rotation matrices. + rotation_vectors: Input batch of rotation vectors. + tol: Small offset for numerical stability. + + Returns: + Updated rotation matrices. + """ + # Convert vector to matrices. + rmat_right = rotvec_to_rotmat(rotation_vectors, tol=tol) + # Accumulate rotation. + rmat_rotated = torch.einsum("...ij,...jk->...ik", rotation_matrices, rmat_right) + return rmat_rotated + + +def rotmat_to_skew_matrix(mat: torch.Tensor) -> torch.Tensor: + """ + Generates skew matrix for corresponding rotation matrix. + + Args: + mat (torch.Tensor): Batch of rotation matrices. + + Returns: + torch.Tensor: Skew matrices in the shapes of mat. + """ + vec = rotmat_to_rotvec(mat) + return vector_to_skew_matrix(vec) + + +def skew_matrix_to_rotmat(skew: torch.Tensor) -> torch.Tensor: + """ + Generates rotation matrix for corresponding skew matrix. + + Args: + skew (torch.Tensor): Batch of target 3 by 3 skew symmetric matrices. + + Returns: + torch.Tensor: Rotation matrices in the shapes of skew. + """ + vec = skew_matrix_to_vector(skew) + return rotvec_to_rotmat(vec) + + +def local_log(point: torch.Tensor, base_point: torch.Tensor) -> torch.Tensor: + """ + Matrix logarithm. Computes left-invariant vector field of beinging base_point to point + on the manifold. Follows the signature of geomstats' equivalent function. + https://geomstats.github.io/api/geometry.html#geomstats.geometry.lie_group.MatrixLieGroup.log + + Args: + point (torch.Tensor): Batch of rotation matrices to compute vector field at. + base_point (torch.Tensor): Transport coordinates to take matrix logarithm. + + Returns: + torch.Tensor: Skew matrix that holds the vector field (in the tangent space). + """ + return rotmat_to_skew_matrix(rot_mult(rot_transpose(base_point), point)) + + +def multidim_trace(mat: torch.Tensor) -> torch.Tensor: + """Take the trace of a matrix with leading dimensions.""" + return torch.einsum("...ii->...", mat) + + +def geodesic_dist(mat_1: torch.Tensor, mat_2: torch.Tensor) -> torch.Tensor: + """ + Calculate the geodesic distance of two rotation matrices. + + Args: + mat_1 (torch.Tensor): First rotation matrix. + mat_2 (torch.Tensor): Second rotation matrix. + + Returns: + Scalar for the geodesic distance between mat_1 and mat_2 with the same + leading (i.e. batch) dimensions. + """ + A = rotmat_to_skew_matrix(rot_mult(rot_transpose(mat_1), mat_2)) + return torch.sqrt(multidim_trace(rot_mult(A, rot_transpose(A)))) + + +def rot_transpose(mat: torch.Tensor) -> torch.Tensor: + """Take the transpose of the last two dimensions.""" + return torch.transpose(mat, -1, -2) + + +def rot_mult(mat_1: torch.Tensor, mat_2: torch.Tensor) -> torch.Tensor: + """Matrix multiply two rotation matrices with leading dimensions.""" + return torch.einsum("...ij,...jk->...ik", mat_1, mat_2) + + +def calc_rot_vf(mat_t: torch.Tensor, mat_1: torch.Tensor) -> torch.Tensor: + """ + Computes the vector field Log_{mat_t}(mat_1). + + Args: + mat_t (torch.Tensor): base point to compute vector field at. + mat_1 (torch.Tensor): target rotation. + + Returns: + Rotation vector representing the vector field. + """ + return rotmat_to_rotvec(rot_mult(rot_transpose(mat_t), mat_1)) + + +def geodesic_t(t: float, mat: torch.Tensor, base_mat: torch.Tensor, rot_vf=None) -> torch.Tensor: + """ + Computes the geodesic at time t. Specifically, R_t = Exp_{base_mat}(t * Log_{base_mat}(mat)). + + Args: + t: time along geodesic. + mat: target points on manifold. + base_mat: source point on manifold. + + Returns: + Point along geodesic starting at base_mat and ending at mat. + """ + if rot_vf is None: + rot_vf = calc_rot_vf(base_mat, mat) + mat_t = rotvec_to_rotmat(t * rot_vf) + if base_mat.shape != mat_t.shape: + raise ValueError( + f'Incompatible shapes: base_mat={base_mat.shape}, mat_t={mat_t.shape}') + return torch.einsum("...ij,...jk->...ik", base_mat, mat_t) + + +class SO3LookupCache: + def __init__( + self, + cache_dir: str, + cache_file: str, + overwrite: bool = False, + ) -> None: + """ + Auxiliary class for handling storage / loading of SO(3) lookup tables in npz format. + + Args: + cache_dir: Path to the cache directory. + cache_file: Basic file name of the cache file. + overwrite: Whether existing cache files should be overwritten if requested. + """ + if not cache_file.endswith(".npz"): + raise ValueError("Filename should have '.npz' extension.") + self.cache_file = cache_file + self.cache_dir = cache_dir + self.cache_path = os.path.join(cache_dir, cache_file) + self.overwrite = overwrite + + @property + def path_exists(self) -> bool: + return os.path.exists(self.cache_path) + + @property + def dir_exists(self) -> bool: + return os.path.exists(self.cache_dir) + + def delete_cache(self) -> None: + """ + Delete the cache file. + """ + if self.path_exists: + os.remove(self.cache_path) + + def load_cache(self) -> Dict[str, torch.Tensor]: + """ + Load data from the cache file. + + Returns: + Dictionary of loaded data tensors. + """ + if self.path_exists: + # Load data and convert to torch tensors. + npz_data = np.load(self.cache_path) + torch_dict = {f: torch.from_numpy(npz_data[f]) for f in npz_data.files} + logger.info(f"Data loaded from {self.cache_path}") + return torch_dict + else: + raise ValueError(f"No cache data found at {self.cache_path}.") + + def save_cache(self, data: Dict[str, torch.Tensor]) -> None: + """ + Save a dictionary of tensors to the cache file. If overwrite is set to True, an existing + file is overwritten, otherwise a warning is raised and the file is not modified. + + Args: + data: Dictionary of tensors that should be saved to the cache. + """ + if not self.dir_exists: + os.makedirs(self.cache_dir) + + if self.path_exists: + if self.overwrite: + logger.info("Overwriting cache ...") + self.delete_cache() + else: + logger.warn( + f"Cache at {self.cache_path} exits and overwriting disabled. Doing nothing." + ) + else: + # Move everything to CPU and numpy and store. + logger.info(f"Data saved to {self.cache_path}") + numpy_dict = {k: v.detach().cpu().numpy() for k, v in data.items()} + np.savez(self.cache_path, **numpy_dict) + + +class BaseSampleSO3(nn.Module): + so3_type: str = "base" # cache basename + + def __init__( + self, + num_omega: int, + sigma_grid: torch.Tensor, + omega_exponent: int = 3, + tol: float = 1e-7, + interpolate: bool = True, + cache_dir: Optional[str] = None, + overwrite_cache: bool = False, + device: str = 'cpu', + ) -> None: + """ + Base torch.nn module for sampling rotations from the IGSO(3) distribution. Samples are + created by uniformly sampling a rotation axis and using inverse transform sampling for + the angles. The latter uses the associated SO(3) cumulative probability distribution + function (CDF) and a uniform distribution [0,1] as described in [#leach2022_1]_. CDF values + are obtained by numerically integrating the probability distribution evaluated on a grid of + angles and noise levels and stored in a lookup table. Linear interpolation is used to + approximate continuos sampling of the function. Angles are discretized in an interval [0,pi] + and the grid can be squashed to have higher resolutions at low angles by taking different + powers. Since sampling relies on tabulated values of the CDF and indexing in the form of + `torch.bucketize`, gradients are not supported. + + Args: + num_omega (int): Number of discrete angles used for generating the lookup table. + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + omega_exponent (int, optional): Make the angle grid denser for smaller angles by taking + its power with the provided number. Defaults to 3. + tol (float, optional): Small value for numerical stability. Defaults to 1e-7. + interpolate (bool, optional): If enables, perform linear interpolation of the angle CDF + to sample angles. Otherwise the closest tabulated point is returned. Defaults to True. + cache_dir: Path to an optional cache directory. If set to None, lookup tables are + computed on the fly. + overwrite_cache: If set to true, existing cache files are overwritten. Can be used for + updating stale caches. + + References + ---------- + .. [#leach2022_1] Leach, Schmon, Degiacomi, Willcocks: + Denoising diffusion probabilistic models on so (3) for rotational alignment. + ICLR 2022 Workshop on Geometrical and Topological Representation Learning. 2022. + """ + super().__init__() + self.num_omega = num_omega + self.omega_exponent = omega_exponent + self.tol = tol + self.interpolate = interpolate + self.device = device + self.register_buffer("sigma_grid", sigma_grid, persistent=False) + + # Generate / load lookups and store in non-persistent buffers. + omega_grid, cdf_igso3 = self._setup_lookup(sigma_grid, cache_dir, overwrite_cache) + self.register_buffer("omega_grid", omega_grid, persistent=False) + self.register_buffer("cdf_igso3", cdf_igso3, persistent=False) + + def _setup_lookup( + self, + sigma_grid: torch.Tensor, + cache_dir: Optional[str] = None, + overwrite_cache: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Master function for setting up the lookup tables. These can either be loaded from a npz + cache file or computed on the fly. Lookup tables will always be created and stored in double + precision. Casting to the target dtype is done at the end of the function. + + Args: + sigma_grid: Grid of sigma values used for computing the lookup tables. + cache_dir: Path to the cache directory. + overwrite_cache: If set to true, an existing cache is overwritten. Can be used for + updating stale caches. + + Returns: + Grid of angle values and SO(3) cumulative distribution function. + """ + if cache_dir is not None: + cache_name = self._get_cache_name() + cache = SO3LookupCache(cache_dir, cache_name, overwrite=True) + + # If cache dir is provided, check whether the necessary cache exists and whether it + # should be overwritten. + if cache.path_exists and not overwrite_cache: + # Load data from cache. + cache_data = cache.load_cache() + omega_grid = cache_data["omega_grid"] + cdf_igso3 = cache_data["cdf_igso3"] + else: + # Store data in cache (overwrite if requested). + omega_grid, cdf_igso3 = self._generate_lookup(sigma_grid) + cache.save_cache({"omega_grid": omega_grid, "cdf_igso3": cdf_igso3}) + else: + # Other wise just generate the tables. + omega_grid, cdf_igso3 = self._generate_lookup(sigma_grid) + + return omega_grid.to(sigma_grid.dtype), cdf_igso3.to(sigma_grid.dtype) + + def _get_cache_name(self) -> str: + """ + Auxiliary function for determining the cache file name based on the parameters (sigma, + omega, l, etc.) used for generating the lookup tables. + + Returns: + Base name of the cache file. + """ + cache_name = "cache_{:s}_s{:04.3f}-{:04.3f}-{:d}_o{:d}-{:d}.npz".format( + self.so3_type, + torch.min(self.sigma_grid).cpu().item(), + torch.max(self.sigma_grid).cpu().item(), + self.sigma_grid.shape[0], + self.num_omega, + self.omega_exponent, + ) + return cache_name + + def get_sigma_idx(self, sigma: torch.Tensor) -> torch.Tensor: + """ + Convert continuous sigmas to the indices of the closest tabulated values. + + Args: + sigma (torch.Tensor): IGSO3 std devs. + + Returns: + torch.Tensor: Index tensor mapping the provided sigma values to the internal lookup + table. + """ + return torch.bucketize(sigma, self.sigma_grid) + + def expansion_function( + self, omega_grid: torch.Tensor, sigma_grid: torch.Tensor + ) -> torch.Tensor: + """ + Function for generating the angle probability distribution. Should return a 2D tensor with + values for the std dev at the first dimension (rows) and angles at the second + (columns). + + Args: + omega_grid (torch.Tensor): Grid of angle values. + sigma_grid (torch.Tensor): IGSO3 std devs. + + Returns: + torch.Tensor: Distribution for angles discretized on a 2D grid. + """ + raise NotImplementedError + + @torch.no_grad() + def _generate_lookup(self, sigma_grid: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Generate the lookup table for sampling from the target SO(3) CDF. The table is 2D, with the + rows corresponding to different sigma values and the columns with angles computed on a grid. + Variance is scaled by a factor of 1/2 to account for the deacceleration of time in the + diffusion process due to the choice of SO(3) basis and guarantee time-reversibility (see + appendix E.3 in [#yim2023_2]_). The returned tables are double precision and will be cast + to the target dtype in `_setup_lookup`. + + Args: + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Tuple containing the grid used to compute the angles + and the associated lookup table. + + References + ---------- + .. [#yim2023_2] Yim, Trippe, De Bortoli, Mathieu, Doucet, Barzilay, Jaakkola: + SE(3) diffusion model with application to protein backbone generation. + arXiv preprint arXiv:2302.02277. 2023. + """ + + current_device = sigma_grid.device + sigma_grid_tmp = sigma_grid.to(torch.float64) + + # If cuda is available, initialize everything on GPU. + # Even if Pytorch Lightning usually handles GPU allocation after initialization, this is + # required to initialize the module in GPU reducing the initializaiton time by orders of magnitude. + if torch.cuda.is_available(): + sigma_grid_tmp = sigma_grid_tmp.to(device=self.device) + + # Set up grid for angle resolution. Convert to double precision for better handling of numerics. + omega_grid = torch.linspace(0.0, 1, self.num_omega + 1).to(sigma_grid_tmp) + + # If requested, increase sample density for lower values + omega_grid = omega_grid**self.omega_exponent + + omega_grid = omega_grid * np.pi + + # Compute the expansion for all omegas and sigmas. + pdf_igso3 = self.expansion_function(omega_grid, sigma_grid_tmp) + + # Apply the pre-factor from USO(3). + pdf_igso3 = pdf_igso3 * (1.0 - torch.cos(omega_grid)) / np.pi + + # Compute the cumulative probability distribution. + cdf_igso3 = integrate_trapezoid_cumulative(pdf_igso3, omega_grid) + # Normalize integral area to 1. + cdf_igso3 = cdf_igso3 / cdf_igso3[:, -1][:, None] + + # Move back to original device. + cdf_igso3 = cdf_igso3.to(device=current_device) + omega_grid = omega_grid.to(device=current_device) + + return omega_grid[1:].to(sigma_grid.dtype), cdf_igso3.to(sigma_grid.dtype) + + def sample(self, sigma: torch.Tensor, num_samples: int) -> torch.Tensor: + """ + Generate samples from the target SO(3) distribution by sampling a rotation axis angle, + which are then combined into a rotation vector and transformed into the corresponding + rotation matrix via an exponential map. + + Args: + sigma_indices (torch.Tensor): Indices of the IGSO3 std devs for which to take samples. + num_samples (int): Number of angle samples to take for each std dev + + Returns: + torch.Tensor: Sampled rotations in matrix representation with dimensions + [num_sigma x num_samples x 3 x 3]. + """ + + vectors = self.sample_vector(sigma.shape[0], num_samples) + angles = self.sample_angle(sigma, num_samples) + + # Do postprocessing on angles. + angles = self._process_angles(sigma, angles) + + rotation_vectors = vectors * angles[..., None] + + rotation_matrices = rotvec_to_rotmat(rotation_vectors, tol=self.tol) + return rotation_matrices + + def _process_angles(self, sigma: torch.Tensor, angles: torch.Tensor) -> torch.Tensor: + """ + Auxiliary function for performing additional processing steps on the sampled angles. One + example would be to ensure sampled angles are 0 for a std dev of 0 for IGSO(3). + + Args: + sigma (torch.Tensor): Current values of sigma. + angles (torch.Tensor): Sampled angles. + + Returns: + torch.Tensor: Processed sampled angles. + """ + return angles + + def sample_vector(self, num_sigma: int, num_samples: int) -> torch.Tensor: + """ + Uniformly sample rotation axis for constructing the overall rotation. + + Args: + num_sigma (int): Number of samples to draw for each std dev. + num_samples (int): Number of angle samples to take for each std dev. + + Returns: + torch.Tensor: Batch of rotation axes with dimensions [num_sigma x num_samples x 3]. + """ + vectors = torch.randn(num_sigma, num_samples, 3, device=self.sigma_grid.device) + vectors = vectors / torch.norm(vectors, dim=2, keepdim=True) + return vectors + + def sample_angle(self, sigma: torch.Tensor, num_samples: int) -> torch.Tensor: + """ + Create a series of samples from the IGSO(3) angle distribution. + + Args: + sigma_indices (torch.Tensor): Indices of the IGSO3 std deves for which to + take samples. + num_samples (int): Number of angle samples to take for each std dev. + + Returns: + torch.Tensor: Collected samples, will have the dimension [num_sigma x num_samples]. + """ + # Convert sigmas to respective indices for lookup table. + sigma_indices = self.get_sigma_idx(sigma) + # Get relevant sigma slices from stored CDFs. + cdf_tmp = self.cdf_igso3[sigma_indices, :] + + # Draw from uniform distribution. + p_uniform = torch.rand((*sigma_indices.shape, *[num_samples]), device=sigma_indices.device) + + # Determine indices for CDF. + idx_stop = torch.sum(cdf_tmp[..., None] < p_uniform[:, None, :], dim=1).long() + idx_start = torch.clamp(idx_stop - 1, min=0) + + if not self.interpolate: + omega = torch.gather(cdf_tmp, dim=1, index=idx_stop) + else: + # Get CDF values. + cdf_start = torch.gather(cdf_tmp, dim=1, index=idx_start) + cdf_stop = torch.gather(cdf_tmp, dim=1, index=idx_stop) + + # Compute weights for linear interpolation. + cdf_delta = torch.clamp(cdf_stop - cdf_start, min=self.tol) + cdf_weight = torch.clamp((p_uniform - cdf_start) / cdf_delta, min=0.0, max=1.0) + + # Get angle range for interpolation. + omega_start = self.omega_grid[idx_start] + omega_stop = self.omega_grid[idx_stop] + + # Interpolate. + omega = torch.lerp(omega_start, omega_stop, cdf_weight) + + return omega + + +class SampleIGSO3(BaseSampleSO3): + so3_type = "igso3" # cache basename + + def __init__( + self, + num_omega: int, + sigma_grid: torch.Tensor, + omega_exponent: int = 3, + tol: float = 1e-7, + interpolate: bool = True, + l_max: int = 1000, + cache_dir: Optional[str] = None, + overwrite_cache: bool = False, + device: str = 'cpu', + ) -> None: + """ + Module for sampling rotations from the IGSO(3) distribution using the explicit series + expansion. Samples are created using inverse transform sampling based on the associated + cumulative probability distribution function (CDF) and a uniform distribution [0,1] as + described in [#leach2022_2]_. CDF values are obtained by numerically integrating the + probability distribution evaluated on a grid of angles and noise levels and stored in a + lookup table. Linear interpolation is used to approximate continuos sampling of the + function. Angles are discretized in an interval [0,pi] and the grid can be squashed to have + higher resolutions at low angles by taking different powers. + Since sampling relies on tabulated values of the CDF and indexing in the form of + `torch.bucketize`, gradients are not supported. + + Args: + num_omega (int): Number of discrete angles used for generating the lookup table. + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + omega_exponent (int, optional): Make the angle grid denser for smaller angles by taking + its power with the provided number. Defaults to 3. + tol (float, optional): Small value for numerical stability. Defaults to 1e-7. + interpolate (bool, optional): If enables, perform linear interpolation of the angle CDF + to sample angles. Otherwise the closest tabulated point is returned. Defaults to True. + l_max (int, optional): Maximum number of terms used in the series expansion. + cache_dir: Path to an optional cache directory. If set to None, lookup tables are + computed on the fly. + overwrite_cache: If set to true, existing cache files are overwritten. Can be used for + updating stale caches. + + References + ---------- + .. [#leach2022_2] Leach, Schmon, Degiacomi, Willcocks: + Denoising diffusion probabilistic models on so (3) for rotational alignment. + ICLR 2022 Workshop on Geometrical and Topological Representation Learning. 2022. + """ + self.l_max = l_max + super().__init__( + num_omega=num_omega, + sigma_grid=sigma_grid, + omega_exponent=omega_exponent, + tol=tol, + interpolate=interpolate, + cache_dir=cache_dir, + overwrite_cache=overwrite_cache, + device=device, + ) + + def _get_cache_name(self) -> str: + """ + Auxiliary function for determining the cache file name based on the parameters (sigma, + omega, l, etc.) used for generating the lookup tables. + + Returns: + Base name of the cache file. + """ + cache_name = "cache_{:s}_s{:04.3f}-{:04.3f}-{:d}_l{:d}_o{:d}-{:d}.npz".format( + self.so3_type, + torch.min(self.sigma_grid).cpu().item(), + torch.max(self.sigma_grid).cpu().item(), + self.sigma_grid.shape[0], + self.l_max, + self.num_omega, + self.omega_exponent, + ) + return cache_name + + def expansion_function( + self, + omega_grid: torch.Tensor, + sigma_grid: torch.Tensor, + ) -> torch.Tensor: + """ + Use the truncated expansion of the IGSO(3) probability function to generate the lookup table. + + Args: + omega_grid (torch.Tensor): Grid of angle values. + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + + Returns: + torch.Tensor: IGSO(3) distribution for angles discretized on a 2D grid. + """ + return generate_igso3_lookup_table(omega_grid, sigma_grid, l_max=self.l_max, tol=self.tol) + + def _process_angles(self, sigma: torch.Tensor, angles: torch.Tensor) -> torch.Tensor: + """ + Ensure sampled angles are 0 for small noise levels in IGSO(3). (Series expansion gives + uniform probability distribution.) + + Args: + sigma (torch.Tensor): Current values of sigma. + angles (torch.Tensor): Sampled angles. + + Returns: + torch.Tensor: Processed sampled angles. + """ + angles = torch.where( + sigma[..., None] < self.tol, + torch.zeros_like(angles), + angles, + ) + return angles + + +class SampleUSO3(BaseSampleSO3): + so3_type = "uso3" # cache basename + + def __init__( + self, + num_omega: int, + sigma_grid: torch.Tensor, + omega_exponent: int = 3, + tol: float = 1e-7, + interpolate: bool = True, + cache_dir: Optional[str] = None, + overwrite_cache: bool = False, + ) -> None: + """ + Module for sampling rotations from the USO(3) distribution. Can be used to generate initial + unbiased samples in the reverse process. Samples are created using inverse transform + sampling based on the associated cumulative probability distribution function (CDF) and a + uniform distribution [0,1] as described in [#leach2022_4]_. CDF values are obtained by + numerically integrating the probability distribution evaluated on a grid of angles and noise + levels and stored in a lookup table. Linear interpolation is used to approximate continuos + sampling of the function. Angles are discretized in an interval [0,pi] and the grid can be + squashed to have higher resolutions at low angles by taking different powers. + Since sampling relies on tabulated values of the CDF and indexing in the form of + `torch.bucketize`, gradients are not supported. + + Args: + num_omega (int): Number of discrete angles used for generating the lookup table. + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + omega_exponent (int, optional): Make the angle grid denser for smaller angles by taking + its power with the provided number. Defaults to 3. + tol (float, optional): Small value for numerical stability. Defaults to 1e-7. + interpolate (bool, optional): If enables, perform linear interpolation of the angle CDF + to sample angles. Otherwise the closest tabulated point is returned. Defaults to True. + cache_dir: Path to an optional cache directory. If set to None, lookup tables are + computed on the fly. + overwrite_cache: If set to true, existing cache files are overwritten. Can be used for + updating stale caches. + + References + ---------- + .. [#leach2022_4] Leach, Schmon, Degiacomi, Willcocks: + Denoising diffusion probabilistic models on so (3) for rotational alignment. + ICLR 2022 Workshop on Geometrical and Topological Representation Learning. 2022. + """ + super().__init__( + num_omega=num_omega, + sigma_grid=sigma_grid, + omega_exponent=omega_exponent, + tol=tol, + interpolate=interpolate, + cache_dir=cache_dir, + overwrite_cache=overwrite_cache, + ) + + def get_sigma_idx(self, sigma: torch.Tensor) -> torch.Tensor: + return torch.zeros_like(sigma).long() + + def sample_shape(self, num_sigma: int, num_samples: int) -> torch.Tensor: + dummy_sigma = torch.zeros(num_sigma, device=self.sigma_grid.device) + return self.sample(dummy_sigma, num_samples) + + def expansion_function( + self, + omega_grid: torch.Tensor, + sigma_grid: torch.Tensor, + ) -> torch.Tensor: + """ + The probability density function of the uniform SO(3) distribution is the cosine scaling + term (1-cos(omega))/pi which is applied automatically during sampling. This means, it is + sufficient to return a tensor of ones to create the correct USO(3) lookup table. + + Args: + omega_grid (torch.Tensor): Grid of angle values. + sigma_grid (torch.Tensor): Grid of IGSO3 std devs. + + Returns: + torch.Tensor: USO(3) distribution for angles discretized on a 2D grid. + """ + return torch.ones(1, omega_grid.shape[0], device=omega_grid.device) + + +@torch.no_grad() +def integrate_trapezoid_cumulative(f_grid: torch.Tensor, x_grid: torch.Tensor) -> torch.Tensor: + """ + Auxiliary function for numerically integrating a discretized 1D function using the trapezoid + rule. This is mainly used for computing the cumulative probability distributions for sampling + from the IGSO(3) distribution. Works on a single 1D grid or a batch of grids. + + Args: + f_grid (torch.Tensor): Discretized function values. + x_grid (torch.Tensor): Discretized input values. + + Returns: + torch.Tensor: Integrated function (not normalized). + """ + f_sum = f_grid[..., :-1] + f_grid[..., 1:] + delta_x = torch.diff(x_grid, dim=-1) + integral = torch.cumsum((f_sum * delta_x[None, :]) / 2.0, dim=-1) + return integral + + +def uniform_so3_density(omega: torch.Tensor) -> torch.Tensor: + """ + Compute the density over the uniform angle distribution in SO(3). + + Args: + omega: Angles in radians. + + Returns: + Uniform distribution density. + """ + return (1.0 - torch.cos(omega)) / np.pi + + +def igso3_expansion( + omega: torch.Tensor, sigma: torch.Tensor, l_grid: torch.Tensor, tol=1e-7 +) -> torch.Tensor: + """ + Compute the IGSO(3) angle probability distribution function for pairs of angles and std dev + levels. The expansion is computed using a grid of expansion orders ranging from 0 to l_max. + + This function approximates the power series in equation 5 of [#yim2023_3]_. With this + parameterization, IGSO(3) agrees with the Brownian motion on SO(3) with t=sigma^2. + + Args: + omega: Values of angles (1D tensor). + sigma: Values of std dev of IGSO3 distribution (1D tensor of same shape as `omega`). + l_grid: Tensor containing expansion orders (0 to l_max). + tol: Small offset for numerical stability. + + Returns: + IGSO(3) angle distribution function (without pre-factor for uniform SO(3) distribution). + + References + ---------- + .. [#yim2023_3] Yim, Trippe, De Bortoli, Mathieu, Doucet, Barzilay, Jaakkola: + SE(3) diffusion model with application to protein backbone generation. + arXiv preprint arXiv:2302.02277. 2023. + """ + # Pre-compute sine in denominator and clamp for stability. + denom_sin = torch.sin(0.5 * omega) + + # Pre-compute terms that rely only on expansion orders. + l_fac_1 = 2.0 * l_grid + 1.0 + l_fac_2 = -l_grid * (l_grid + 1.0) + + # Pre-compute numerator of expansion which only depends on angles. + numerator_sin = torch.sin((l_grid[None, :] + 1 / 2) * omega[:, None]) + + # Pre-compute exponential term with (2l+1) prefactor. + exponential_term = l_fac_1[None, :] * torch.exp(l_fac_2[None, :] * sigma[:, None] ** 2 / 2) + + # Compute series expansion + f_igso = torch.sum(exponential_term * numerator_sin, dim=1) + # For small omega, accumulate limit of sine fraction instead: + # lim[x->0] sin((l+1/2)x) / sin(x/2) = 2l + 1 + f_limw = torch.sum(exponential_term * l_fac_1[None, :], dim=1) + + # Finalize expansion. Offset for stability can be added since omega is [0,pi] and sin(omega/2) + # is positive in this interval. + f_igso = f_igso / (denom_sin + tol) + + # Replace values at small omega with limit. + f_igso = torch.where(omega <= tol, f_limw, f_igso) + + # Remove remaining numerical problems + f_igso = torch.where( + torch.logical_or(torch.isinf(f_igso), torch.isnan(f_igso)), torch.zeros_like(f_igso), f_igso + ) + + return f_igso + + +def digso3_expansion( + omega: torch.Tensor, sigma: torch.Tensor, l_grid: torch.Tensor, tol=1e-7 +) -> torch.Tensor: + r""" + Compute the derivative of the IGSO(3) angle probability distribution function with respect to + the angles for pairs of angles and std dev levels. As in `igso3_expansion` a grid is used for the + expansion levels. Evaluates the derivative directly in order to avoid second derivatives during + backpropagation. + + The derivative of the angle-dependent part is computed as: + + .. math:: + \frac{\partial}{\partial \omega} \frac{\sin((l+\tfrac{1}{2})\omega)}{\sin(\tfrac{1}{2}\omega)} = \frac{l\sin((l+1)\omega) - (l+1)\sin(l\omega)}{1 - \cos(\omega)} + + (obtained via quotient rule + different trigonometric identities). + + Args: + omega: Values of angles (1D tensor). + sigma: Values of IGSO3 distribution std devs (1D tensor of same shape as `omega`). + l_grid: Tensor containing expansion orders (0 to l_max). + tol: Small offset for numerical stability. + + Returns: + IGSO(3) angle distribution derivative (without pre-factor for uniform SO(3) distribution). + """ + denom_cos = 1.0 - torch.cos(omega) + + l_fac_1 = 2.0 * l_grid + 1.0 + l_fac_2 = l_grid + 1.0 + l_fac_3 = -l_grid * l_fac_2 + + # Pre-compute numerator of expansion which only depends on angles. + numerator_sin = l_grid[None, :] * torch.sin(l_fac_2[None, :] * omega[:, None]) - l_fac_2[ + None, : + ] * torch.sin(l_grid[None, :] * omega[:, None]) + + # Compute series expansion + df_igso = torch.sum( + l_fac_1[None, :] * torch.exp(l_fac_3[None, :] * sigma[:, None] ** 2 / 2) * numerator_sin, + dim=1, + ) + + # Finalize expansion. Offset for stability can be added since omega is [0,pi] and cosine term + # is positive in this interval. + df_igso = df_igso / (denom_cos + tol) + + # Replace values at small omega with limit (=0). + df_igso = torch.where(omega <= tol, torch.zeros_like(df_igso), df_igso) + + # Remove remaining numerical problems + df_igso = torch.where( + torch.logical_or(torch.isinf(df_igso), torch.isnan(df_igso)), + torch.zeros_like(df_igso), + df_igso, + ) + + return df_igso + + +def dlog_igso3_expansion( + omega: torch.Tensor, sigma: torch.Tensor, l_grid: torch.Tensor, tol=1e-7 +) -> torch.Tensor: + r""" + Compute the derivative of the logarithm of the IGSO(3) angle distribution function for pairs of + angles and std dev levels: + + .. math:: + \frac{\partial}{\partial \omega} \log f(\omega) = \frac{\tfrac{\partial}{\partial \omega} f(\omega)}{f(\omega)} + + Required for SO(3) score computation. + + Args: + omega: Values of angles (1D tensor). + sigma: Values of IGSO3 std devs (1D tensor of same shape as `omega`). + l_grid: Tensor containing expansion orders (0 to l_max). + tol: Small offset for numerical stability. + + Returns: + IGSO(3) angle distribution derivative (without pre-factor for uniform SO(3) distribution). + """ + f_igso3 = igso3_expansion(omega, sigma, l_grid, tol=tol) + df_igso3 = digso3_expansion(omega, sigma, l_grid, tol=tol) + + return df_igso3 / (f_igso3 + tol) + + +@torch.no_grad() +def generate_lookup_table( + base_function: Callable, + omega_grid: torch.Tensor, + sigma_grid: torch.Tensor, + l_max: int = 1000, + tol: float = 1e-7, +): + """ + Auxiliary function for generating a lookup table from IGSO(3) expansions and their derivatives. + Takes a basic function and loops over different std dev levels. + + Args: + base_function: Function used for setting up the lookup table. + omega_grid: Grid of angle values ranging from [0,pi] (shape is[num_omega]). + sigma_grid: Grid of IGSO3 std dev values (shape is [num_sigma]). + l_max: Number of terms used in the series expansion. + tol: Small value for numerical stability. + + Returns: + Table of function values evaluated at different angles and std dev levels. The final shape is + [num_sigma x num_omega]. + """ + # Generate grid of expansion orders. + l_grid = torch.arange(l_max + 1, device=omega_grid.device).to(omega_grid.dtype) + + n_omega = len(omega_grid) + n_sigma = len(sigma_grid) + + # Populate lookup table for different time frames. + f_table = torch.zeros(n_sigma, n_omega, device=omega_grid.device, dtype=omega_grid.dtype) + + for eps_idx in tqdm(range(n_sigma), desc=f"Computing {base_function.__name__}"): + f_table[eps_idx, :] = base_function( + omega_grid, + torch.ones_like(omega_grid) * sigma_grid[eps_idx], + l_grid, + tol=tol, + ) + + return f_table + + +def generate_igso3_lookup_table( + omega_grid: torch.Tensor, + sigma_grid: torch.Tensor, + l_max: int = 1000, + tol: float = 1e-7, +) -> torch.Tensor: + """ + Generate a lookup table for the IGSO(3) probability distribution function of angles. + + Args: + omega_grid: Grid of angle values ranging from [0,pi] (shape is[num_omega]). + sigma_grid: Grid of IGSO3 std dev values (shape is [num_sigma]). + l_max: Number of terms used in the series expansion. + tol: Small value for numerical stability. + + Returns: + Table of function values evaluated at different angles and std dev levels. The final shape is + [num_sigma x num_omega]. + """ + f_igso = generate_lookup_table( + base_function=igso3_expansion, + omega_grid=omega_grid, + sigma_grid=sigma_grid, + l_max=l_max, + tol=tol, + ) + return f_igso + + +def generate_dlog_igso3_lookup_table( + omega_grid: torch.Tensor, + sigma_grid: torch.Tensor, + l_max: int = 1000, + tol: float = 1e-7, +) -> torch.Tensor: + """ + Generate a lookup table for the derivative of the logarithm of the angular IGSO(3) probability + distribution function. Used e.g. for computing scaling of SO(3) norms. + + Args: + omega_grid: Grid of angle values ranging from [0,pi] (shape is[num_omega]). + sigma_grid: Grid of IGSO3 std dev values (shape is [num_sigma]). + l_max: Number of terms used in the series expansion. + tol: Small value for numerical stability. + + Returns: + Table of function values evaluated at different angles and std dev levels. The final shape is + [num_sigma x num_omega]. + """ + dlog_igso = generate_lookup_table( + base_function=dlog_igso3_expansion, + omega_grid=omega_grid, + sigma_grid=sigma_grid, + l_max=l_max, + tol=tol, + ) + return dlog_igso diff --git a/gafl/gafl/data/utils.py b/gafl/gafl/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e388e70a6459c3aa46b355e5acf8ca568739586b --- /dev/null +++ b/gafl/gafl/data/utils.py @@ -0,0 +1,800 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from typing import List, Dict, Any +from openfold.utils import rigid_utils as ru +import numpy as np +import collections +import string +import pickle +import os +import torch +import mdtraj as md +from torch_scatter import scatter_add, scatter +from Bio.PDB.Chain import Chain +import dataclasses +from Bio import PDB +import biotite.structure as struc +import io +import pandas as pd +from pathlib import Path +import warnings + +from gafl.data import protein +from gafl.data import residue_constants + + +Rigid = ru.Rigid +Protein = protein.Protein + +PICKLE_EXTENSIONS = ['.pkl', '.pickle', '.pck', '.db', '.pck'] + +# Global map from chain characters to integers. +ALPHANUMERIC = string.ascii_letters + string.digits + ' ' +CHAIN_TO_INT = { + chain_char: i for i, chain_char in enumerate(ALPHANUMERIC) +} +INT_TO_CHAIN = { + i: chain_char for i, chain_char in enumerate(ALPHANUMERIC) +} + +NM_TO_ANG_SCALE = 10.0 +ANG_TO_NM_SCALE = 1 / NM_TO_ANG_SCALE + +CHAIN_FEATS = [ + 'atom_positions', 'aatype', 'atom_mask', 'residue_index', 'b_factors' +] + +to_numpy = lambda x: x.detach().cpu().numpy() +aatype_to_seq = lambda aatype: ''.join([ + residue_constants.restypes_with_x[x] for x in aatype]) + + +class CPU_Unpickler(pickle.Unpickler): + """Pytorch pickle loading workaround. + + https://github.com/pytorch/pytorch/issues/16797 + """ + def find_class(self, module, name): + if module == 'torch.storage' and name == '_load_from_bytes': + return lambda b: torch.load(io.BytesIO(b), map_location='cpu') + else: return super().find_class(module, name) + + +def create_rigid(rots, trans): + rots = ru.Rotation(rot_mats=rots) + return Rigid(rots=rots, trans=trans) + + +def batch_align_structures(pos_1, pos_2, mask=None): + if pos_1.shape != pos_2.shape: + raise ValueError('pos_1 and pos_2 must have the same shape.') + if pos_1.ndim != 3: + raise ValueError(f'Expected inputs to have shape [B, N, 3]') + num_batch = pos_1.shape[0] + device = pos_1.device + batch_indices = ( + torch.ones(*pos_1.shape[:2], device=device, dtype=torch.int64) + * torch.arange(num_batch, device=device)[:, None] + ) + flat_pos_1 = pos_1.reshape(-1, 3) + flat_pos_2 = pos_2.reshape(-1, 3) + flat_batch_indices = batch_indices.reshape(-1) + if mask is None: + aligned_pos_1, aligned_pos_2, align_rots = align_structures( + flat_pos_1, flat_batch_indices, flat_pos_2) + aligned_pos_1 = aligned_pos_1.reshape(num_batch, -1, 3) + aligned_pos_2 = aligned_pos_2.reshape(num_batch, -1, 3) + return aligned_pos_1, aligned_pos_2, align_rots + + flat_mask = mask.reshape(-1).bool() + _, _, align_rots = align_structures( + flat_pos_1[flat_mask], + flat_batch_indices[flat_mask], + flat_pos_2[flat_mask] + ) + aligned_pos_1 = torch.bmm( + pos_1, + align_rots + ) + return aligned_pos_1, pos_2, align_rots + + +def adjust_oxygen_pos( + atom_37: torch.Tensor, pos_is_known = None +) -> torch.Tensor: + """ + Imputes the position of the oxygen atom on the backbone by using adjacent frame information. + Specifically, we say that the oxygen atom is in the plane created by the Calpha and C from the + current frame and the nitrogen of the next frame. The oxygen is then placed c_o_bond_length Angstrom + away from the C in the current frame in the direction away from the Ca-C-N triangle. + + For cases where the next frame is not available, for example we are at the C-terminus or the + next frame is not available in the data then we place the oxygen in the same plane as the + N-Ca-C of the current frame and pointing in the same direction as the average of the + Ca->C and Ca->N vectors. + + Args: + atom_37 (torch.Tensor): (N, 37, 3) tensor of positions of the backbone atoms in atom_37 ordering + which is ['N', 'CA', 'C', 'CB', 'O', ...] + pos_is_known (torch.Tensor): (N,) mask for known residues. + """ + + N = atom_37.shape[0] + assert atom_37.shape == (N, 37, 3) + + # Get vectors to Carbonly from Carbon alpha and N of next residue. (N-1, 3) + # Note that the (N,) ordering is from N-terminal to C-terminal. + + # Calpha to carbonyl both in the current frame. + calpha_to_carbonyl: torch.Tensor = (atom_37[:-1, 2, :] - atom_37[:-1, 1, :]) / ( + torch.norm(atom_37[:-1, 2, :] - atom_37[:-1, 1, :], keepdim=True, dim=1) + 1e-7 + ) + # For masked positions, they are all 0 and so we add 1e-7 to avoid division by 0. + # The positions are in Angstroms and so are on the order ~1 so 1e-7 is an insignificant change. + + # Nitrogen of the next frame to carbonyl of the current frame. + nitrogen_to_carbonyl: torch.Tensor = (atom_37[:-1, 2, :] - atom_37[1:, 0, :]) / ( + torch.norm(atom_37[:-1, 2, :] - atom_37[1:, 0, :], keepdim=True, dim=1) + 1e-7 + ) + + carbonyl_to_oxygen: torch.Tensor = calpha_to_carbonyl + nitrogen_to_carbonyl # (N-1, 3) + carbonyl_to_oxygen = carbonyl_to_oxygen / ( + torch.norm(carbonyl_to_oxygen, dim=1, keepdim=True) + 1e-7 + ) + + atom_37[:-1, 4, :] = atom_37[:-1, 2, :] + carbonyl_to_oxygen * 1.23 + + # Now we deal with frames for which there is no next frame available. + + # Calpha to carbonyl both in the current frame. (N, 3) + calpha_to_carbonyl_term: torch.Tensor = (atom_37[:, 2, :] - atom_37[:, 1, :]) / ( + torch.norm(atom_37[:, 2, :] - atom_37[:, 1, :], keepdim=True, dim=1) + 1e-7 + ) + # Calpha to nitrogen both in the current frame. (N, 3) + calpha_to_nitrogen_term: torch.Tensor = (atom_37[:, 0, :] - atom_37[:, 1, :]) / ( + torch.norm(atom_37[:, 0, :] - atom_37[:, 1, :], keepdim=True, dim=1) + 1e-7 + ) + carbonyl_to_oxygen_term: torch.Tensor = ( + calpha_to_carbonyl_term + calpha_to_nitrogen_term + ) # (N, 3) + carbonyl_to_oxygen_term = carbonyl_to_oxygen_term / ( + torch.norm(carbonyl_to_oxygen_term, dim=1, keepdim=True) + 1e-7 + ) + + # Create a mask that is 1 when the next residue is not available either + # due to this frame being the C-terminus or the next residue is not + # known due to pos_is_known being false. + + if pos_is_known is None: + pos_is_known = torch.ones((atom_37.shape[0],), dtype=torch.int64, device=atom_37.device) + + next_res_gone: torch.Tensor = ~pos_is_known.bool() # (N,) + next_res_gone = torch.cat( + [next_res_gone, torch.ones((1,), device=pos_is_known.device).bool()], dim=0 + ) # (N+1, ) + next_res_gone = next_res_gone[1:] # (N,) + + atom_37[next_res_gone, 4, :] = ( + atom_37[next_res_gone, 2, :] + + carbonyl_to_oxygen_term[next_res_gone, :] * 1.23 + ) + + return atom_37 + + +def write_pkl( + save_path: str, pkl_data: Any, create_dir: bool = False, use_torch=False): + """Serialize data into a pickle file.""" + if create_dir: + os.makedirs(os.path.dirname(save_path), exist_ok=True) + if use_torch: + torch.save(pkl_data, save_path, pickle_protocol=pickle.HIGHEST_PROTOCOL) + else: + with open(save_path, 'wb') as handle: + pickle.dump(pkl_data, handle, protocol=pickle.HIGHEST_PROTOCOL) + + +def read_pkl(read_path: str, verbose=True, use_torch=False, map_location=None): + """Read data from a pickle file.""" + try: + if use_torch: + return torch.load(read_path, map_location=map_location) + else: + with open(read_path, 'rb') as handle: + return pickle.load(handle) + except Exception as e: + try: + with open(read_path, 'rb') as handle: + return CPU_Unpickler(handle).load() + except Exception as e2: + if verbose: + print(f'Failed to read {read_path}. First error: {e}\n Second error: {e2}') + raise(e) + +def read_npz(npz:dict): + """ + Converts dict of np arrays to a biotite AtomArray object. + Returns: a struc.AtomArray (biotite) object + """ + + coords = npz['coords'] + chain_id = npz['chain_id'] + res_id = npz['res_id'] + res_name = npz['res_name'] + atom_name = npz['atom_name'] + element = npz['element'] + + if 'b_factor' in npz and npz['b_factor'].shape !=(0,): + b_factor = npz['b_factor'] + else: + b_factor = np.zeros(coords.shape[0]) + + # some shape checks: + num_bb_atoms = coords.shape[0] + + assert chain_id.shape[0] == num_bb_atoms, f'chain_id shape {chain_id.shape} does not match coords shape {coords.shape}' + assert res_id.shape[0] == num_bb_atoms, f'res_id shape {res_id.shape} does not match coords shape {coords.shape}' + assert res_name.shape[0] == num_bb_atoms, f'res_name shape {res_name.shape} does not match coords shape {coords.shape}' + assert atom_name.shape[0] == num_bb_atoms, f'atom_name shape {atom_name.shape} does not match coords shape {coords.shape}' + assert element.shape[0] == num_bb_atoms, f'element shape {element.shape} does not match coords shape {coords.shape}' + assert b_factor.shape[0] == num_bb_atoms, f'b_factor shape {b_factor.shape} does not match coords shape {coords.shape}' + + # construct a biotite AtomArray + chain_feats = struc.AtomArray(len(coords)) + chain_feats.coord = coords + chain_feats.chain_id = chain_id + chain_feats.res_id = res_id + chain_feats.res_name = res_name + chain_feats.atom_name = atom_name + chain_feats.element = element + chain_feats.b_factor = b_factor + return chain_feats + +def chain_str_to_int(chain_str: str): + chain_int = 0 + if len(chain_str) == 1: + return CHAIN_TO_INT[chain_str] + for i, chain_char in enumerate(chain_str): + chain_int += CHAIN_TO_INT[chain_char] + (i * len(ALPHANUMERIC)) + return chain_int + + +def parse_chain_feats(chain_feats, scale_factor=1.): + ca_idx = residue_constants.atom_order['CA'] + chain_feats['bb_mask'] = chain_feats['atom_mask'][:, ca_idx] + bb_pos = chain_feats['atom_positions'][:, ca_idx] + bb_center = np.sum(bb_pos, axis=0) / (np.sum(chain_feats['bb_mask']) + 1e-5) + centered_pos = chain_feats['atom_positions'] - bb_center[None, None, :] + scaled_pos = centered_pos / scale_factor + chain_feats['atom_positions'] = scaled_pos * chain_feats['atom_mask'][..., None] + chain_feats['bb_positions'] = chain_feats['atom_positions'][:, ca_idx] + return chain_feats + + +def concat_np_features( + np_dicts: List[Dict[str, np.ndarray]], add_batch_dim: bool): + """Performs a nested concatenation of feature dicts. + + Args: + np_dicts: list of dicts with the same structure. + Each dict must have the same keys and numpy arrays as the values. + add_batch_dim: whether to add a batch dimension to each feature. + + Returns: + A single dict with all the features concatenated. + """ + combined_dict = collections.defaultdict(list) + for chain_dict in np_dicts: + for feat_name, feat_val in chain_dict.items(): + if add_batch_dim: + feat_val = feat_val[None] + combined_dict[feat_name].append(feat_val) + # Concatenate each feature + for feat_name, feat_vals in combined_dict.items(): + combined_dict[feat_name] = np.concatenate(feat_vals, axis=0) + return combined_dict + + +def center_zero(pos: torch.Tensor, batch_indexes: torch.LongTensor) -> torch.Tensor: + """ + Move the molecule center to zero for sparse position tensors. + + Args: + pos: [N, 3] batch positions of atoms in the molecule in sparse batch format. + batch_indexes: [N] batch index for each atom in sparse batch format. + + Returns: + pos: [N, 3] zero-centered batch positions of atoms in the molecule in sparse batch format. + """ + assert len(pos.shape) == 2 and pos.shape[-1] == 3, "pos must have shape [N, 3]" + + means = scatter(pos, batch_indexes, dim=0, reduce="mean") + return pos - means[batch_indexes] + + +@torch.no_grad() +def align_structures( + batch_positions: torch.Tensor, + batch_indices: torch.Tensor, + reference_positions: torch.Tensor, + broadcast_reference: bool = False, +): + """ + Align structures in a ChemGraph batch to a reference, e.g. for RMSD computation. This uses the + sparse formulation of pytorch geometric. If the ChemGraph is composed of a single system, then + the reference can be given as a single structure and broadcasted. Returns the structure + coordinates shifted to the geometric center and the batch structures rotated to match the + reference structures. Uses the Kabsch algorithm (see e.g. [kabsch_align1]_). No permutation of + atoms is carried out. + + Args: + batch_positions (Tensor): Batch of structures (e.g. from ChemGraph) which should be aligned + to a reference. + batch_indices (Tensor): Index tensor mapping each node / atom in batch to the respective + system (e.g. batch attribute of ChemGraph batch). + reference_positions (Tensor): Reference structure. Can either be a batch of structures or a + single structure. In the second case, broadcasting is possible if the input batch is + composed exclusively of this structure. + broadcast_reference (bool, optional): If reference batch contains only a single structure, + broadcast this structure to match the ChemGraph batch. Defaults to False. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Tensors containing the centered positions of batch + structures rotated into the reference and the centered reference batch. + + References + ---------- + .. [kabsch_align1] Lawrence, Bernal, Witzgall: + A purely algebraic justification of the Kabsch-Umeyama algorithm. + Journal of research of the National Institute of Standards and Technology, 124, 1. 2019. + """ + # Minimize || Q @ R.T - P ||, which is the same as || Q - P @ R || + # batch_positions -> P [BN x 3] + # reference_positions -> Q [B / BN x 3] + + if batch_positions.shape[0] != reference_positions.shape[0]: + if broadcast_reference: + # Get number of systems in batch and broadcast reference structure. + # This assumes, all systems in the current batch correspond to the reference system. + # Typically always the case during evaluation. + num_molecules = int(torch.max(batch_indices) + 1) + reference_positions = reference_positions.repeat(num_molecules, 1) + else: + raise ValueError("Mismatch in batch dimensions.") + + # Center structures at origin (takes care of translation alignment) + batch_positions = center_zero(batch_positions, batch_indices) + reference_positions = center_zero(reference_positions, batch_indices) + + # Compute covariance matrix for optimal rotation (Q.T @ P) -> [B x 3 x 3]. + cov = scatter_add( + batch_positions[:, None, :] * reference_positions[:, :, None], batch_indices, dim=0 + ) + + # Perform singular value decomposition. (all [B x 3 x 3]) + u, _, v_t = torch.linalg.svd(cov) + # Convenience transposes. + u_t = u.transpose(1, 2) + v = v_t.transpose(1, 2) + + # Compute rotation matrix correction for ensuring right-handed coordinate system + # For comparison with other sources: det(AB) = det(A)*det(B) and det(A) = det(A.T) + sign_correction = torch.sign(torch.linalg.det(torch.bmm(v.float(), u_t.float()))) + # Correct transpose of U: diag(1, 1, sign_correction) @ U.T + u_t[:, 2, :] = u_t[:, 2, :] * sign_correction[:, None] + + # Compute optimal rotation matrix (R = V @ diag(1, 1, sign_correction) @ U.T). + rotation_matrices = torch.bmm(v, u_t) + + # Rotate batch positions P to optimal alignment with Q (P @ R) + batch_positions_rotated = torch.bmm( + batch_positions[:, None, :], + rotation_matrices[batch_indices], + ).squeeze(1) + + return batch_positions_rotated, reference_positions, rotation_matrices + + +def parse_pdb_feats( + pdb_name: str, + pdb_path: str, + scale_factor=1., + # TODO: Make the default behaviour read all chains. + chain_id='A', + calc_dssp:bool=False + ): + """ + Args: + pdb_name: name of PDB to parse. + pdb_path: path to PDB file to read. + scale_factor: factor to scale atom positions. + mean_center: whether to mean center atom positions. + calc_dssp: whether to compute DSSP features. + Returns: + Dict with CHAIN_FEATS features extracted from PDB with specified + preprocessing. + """ + parser = PDB.PDBParser(QUIET=True) + structure = parser.get_structure(pdb_name, pdb_path) + struct_chains = { + chain.id: chain + for chain in structure.get_chains()} + + def _process_chain_id(x): + if calc_dssp: + chain_prot = process_chain(struct_chains[x], x, pdb_loc=pdb_path, calc_dssp=calc_dssp) + else: + chain_prot = process_chain(struct_chains[x], x) + chain_dict = dataclasses.asdict(chain_prot) + + # Process features + feat_dict = {x: chain_dict[x] for x in (CHAIN_FEATS + ['dssp'] if calc_dssp else CHAIN_FEATS)} + return parse_chain_feats( + feat_dict, scale_factor=scale_factor) + + if isinstance(chain_id, str): + return _process_chain_id(chain_id) + elif isinstance(chain_id, list): + return { + x: _process_chain_id(x) for x in chain_id + } + elif chain_id is None: + return { + x: _process_chain_id(x) for x in struct_chains + } + else: + raise ValueError(f'Unrecognized chain list {chain_id}') + +def parse_npz_feats(npz_feats:struc.AtomArray, + scale_factor=1., + calc_dssp:bool=False): + ''' + Args: + npz_feats: struc.AtomArray extracted from a npz file from read_npz() + scale_factor: factor to scale atom positions. + calc_dssp: whether to compute DSSP features. + Returns: + Dict with CHAIN_FEATS features extracted from the compressed PDB with specified + preprocessing. + ''' + + def _process_chain_id(npz_feats): + chain_prot = process_chain_npz(npz_feats, dssp=calc_dssp) + + chain_dict = dataclasses.asdict(chain_prot) + + feat_dict = {x: chain_dict[x] for x in CHAIN_FEATS} + return parse_chain_feats(feat_dict, + scale_factor=scale_factor) + + if isinstance(npz_feats, struc.AtomArray): + return _process_chain_id(npz_feats) + elif isinstance(npz_feats, list): + return { + x: _process_chain_id(x) for x in npz_feats + } + elif npz_feats is None: + return None + else: + raise ValueError("Invalid input type") + +def rigid_transform_3D(A, B, verbose=False): + # Transforms A to look like B + # https://github.com/nghiaho12/rigid_transform_3D + assert A.shape == B.shape + A = A.T + B = B.T + + num_rows, num_cols = A.shape + if num_rows != 3: + raise Exception(f"matrix A is not 3xN, it is {num_rows}x{num_cols}") + + num_rows, num_cols = B.shape + if num_rows != 3: + raise Exception(f"matrix B is not 3xN, it is {num_rows}x{num_cols}") + + # find mean column wise + centroid_A = np.mean(A, axis=1) + centroid_B = np.mean(B, axis=1) + + # ensure centroids are 3x1 + centroid_A = centroid_A.reshape(-1, 1) + centroid_B = centroid_B.reshape(-1, 1) + + # subtract mean + Am = A - centroid_A + Bm = B - centroid_B + + H = Am @ np.transpose(Bm) + + # sanity check + #if linalg.matrix_rank(H) < 3: + # raise ValueError("rank of H = {}, expecting 3".format(linalg.matrix_rank(H))) + + # find rotation + U, S, Vt = np.linalg.svd(H) + R = Vt.T @ U.T + + # special reflection case + reflection_detected = False + if np.linalg.det(R) < 0: + if verbose: + print("det(R) < R, reflection detected!, correcting for it ...") + Vt[2,:] *= -1 + R = Vt.T @ U.T + reflection_detected = True + + t = -R @ centroid_A + centroid_B + optimal_A = R @ A + t + + return optimal_A.T, R, t, reflection_detected + + +def process_chain(chain: Chain, chain_id: str, pdb_loc=None, calc_dssp=None) -> Protein: + """Convert a PDB chain object into a AlphaFold Protein instance. + + Forked from alphafold.common.protein.from_pdb_string + + WARNING: All non-standard residue types will be converted into UNK. All + non-standard atoms will be ignored. + + Took out lines 94-97 which don't allow insertions in the PDB. + Sabdab uses insertions for the chothia numbering so we need to allow them. + + Took out lines 110-112 since that would mess up CDR numbering. + + Addded: pdb_loc:str and calc_dssp:bool to compute the dssp + + Args: + chain: Instance of Biopython's chain class. + + Returns: + Protein object with protein features. + """ + atom_positions = [] + aatype = [] + atom_mask = [] + residue_index = [] + b_factors = [] + chain_ids = [] + # modified here + if calc_dssp: + assert pdb_loc is not None, 'pdb_loc must be provided to compute dssp' + t = md.load(pdb_loc) # only possible to compute for the refolded designs since they contain [N, CA, C] needed for dihedrals + dssp = md.compute_dssp(t) + dssp = dssp[0] + else: + dssp = None + + for res in chain: + res_shortname = residue_constants.restype_3to1.get(res.resname, 'X') + restype_idx = residue_constants.restype_order.get( + res_shortname, residue_constants.restype_num) + pos = np.zeros((residue_constants.atom_type_num, 3)) + mask = np.zeros((residue_constants.atom_type_num,)) + res_b_factors = np.zeros((residue_constants.atom_type_num,)) + for atom in res: + if atom.name not in residue_constants.atom_types: + continue + pos[residue_constants.atom_order[atom.name]] = atom.coord + mask[residue_constants.atom_order[atom.name]] = 1. + res_b_factors[residue_constants.atom_order[atom.name] + ] = atom.bfactor + aatype.append(restype_idx) + atom_positions.append(pos) + atom_mask.append(mask) + residue_index.append(res.id[1]) + b_factors.append(res_b_factors) + chain_ids.append(chain_id) + + return Protein( + atom_positions=np.array(atom_positions), + atom_mask=np.array(atom_mask), + aatype=np.array(aatype), + residue_index=np.array(residue_index), + chain_index=np.array(chain_ids), + b_factors=np.array(b_factors), + dssp=dssp) + +def process_chain_npz(npz_feats: struc.AtomArray, dssp=None) -> Protein: + ''' + npz_feats: struc.AtomArray extracted from a npz file from read_npz() + dssp: None, cannot be computed for the feats extracted from .npz without writing creating a .pdb file + ''' + residues = npz_feats.res_name[::3] + atoms = npz_feats.atom_name + coords = npz_feats.coord + bfac = npz_feats.b_factor + chain_id = npz_feats.chain_id + res_ids = npz_feats.res_id[::3] + + if len(bfac) == 0: + bfac = np.zeros_like(atoms, dtype=np.float32) + + atom_positions = [] + aatype = [] + atom_mask = [] + residue_index = [] + b_factors = [] + chain_ids = [] + + assert len(residues) > 0, 'No residues found in the npz file' + + for i in range(len(residues)): + + res_shortname = residue_constants.restype_3to1.get(residues[i], 'X') + restype_idx = residue_constants.restype_order.get( + res_shortname, residue_constants.restype_num) + pos = np.zeros((residue_constants.atom_type_num, 3)) + mask = np.zeros((residue_constants.atom_type_num,)) + res_b_factors = np.zeros((residue_constants.atom_type_num,)) + + for index in range(len(atoms[i*3:(i+1)*3])): + if atoms[index] not in residue_constants.atom_types: + continue + pos[residue_constants.atom_order[atoms[index]]] = coords[i*3:(i+1)*3][index] + mask[residue_constants.atom_order[atoms[index]]] = 1. + res_b_factors[residue_constants.atom_order[atoms[index]] + ] = bfac[i*3:(i+1)*3][index] + + aatype.append(restype_idx) + atom_positions.append(pos) + atom_mask.append(mask) + residue_index.append(res_ids[i]) + b_factors.append(res_b_factors) + chain_ids.append(chain_id[i]) + + return Protein( + atom_positions=np.array(atom_positions), + atom_mask=np.array(atom_mask), + aatype=np.array(aatype), + residue_index=np.array(residue_index), + chain_index=np.array(chain_ids), + b_factors=np.array(b_factors), + dssp=dssp) + + +def metadata_naming_convention(df: pd.DataFrame)->pd.DataFrame: + ''' + Renames certain cols in the dataframe to match the naming convention of metadata files + ''' + + # dictionary that maps conventional col name to list of possible col names in the dataframe + RENAME_DICT = { + "pdb_name": ["name_pdb",], + "processed_path": ["location",], + "breaks": ["break",], + "coil_percent": ["pct_coil",], + "helix_percent": ["pct_helix",], + "strand_percent": ["pct_strand",], + "seq_len": ["length",], + } + + for col, possible_names in RENAME_DICT.items(): + for name in possible_names: + if name in df.columns: + df.rename(columns={name: col}, inplace=True) + break + + # for length -> modeled_seq_len, we also need to check that there are no breaks in the proteins: + if "modeled_seq_len" not in df.columns: + if "seq_len" in df.columns: + assert "breaks" in df.columns, "breaks must be in the dataframe to compute modeled_seq_len" + # assert the entry in breaks is always false: + # assert df["breaks"].apply(lambda x: x == False).all(), "breaks must be False for all entries" + df["modeled_seq_len"] = df["seq_len"] + else: + raise ValueError("modeled_seq_len or length must be in the dataframe") + + return df + + +# some filtering utils: +def has_breaks(chain_feats:dict, max_ca_ca_distance=4.5): + ''' + Checks if the entry of PdbDataset has breaks in the backbone based on the ca ca distance (in angstrom, canonical distance is 3.8, 4.5 includes some tolerance). + ''' + # check ca_ca distance: + xyz = chain_feats['trans_1'] + if isinstance(xyz, torch.Tensor): + xyz = xyz.detach().cpu().numpy() + elif isinstance(xyz, list): + xyz = np.array(xyz) + elif not isinstance(xyz, np.ndarray): + raise ValueError(f"xyz must be a torch.Tensor, list or np.ndarray, not {type(xyz)}") + + # calculate distances between subsequent CA atoms: + subsequent_dists = np.linalg.norm(xyz[1:] - xyz[:-1], axis=1) + if not np.all(subsequent_dists < max_ca_ca_distance): + return True + else: + return False + +def has_inconstistent_indexing(chain_feats:dict): + ''' + Checks if the entry of PdbDataset has inconsistent indexing of the residues. + ''' + res_idxs = chain_feats['res_idx'] + if isinstance(res_idxs, torch.Tensor): + res_idxs = res_idxs.detach().cpu().numpy() + elif isinstance(res_idxs, list): + res_idxs = np.array(res_idxs) + elif not isinstance(res_idxs, np.ndarray): + raise ValueError(f"res_idxs must be a torch.Tensor, list or np.ndarray, not {type(res_idxs)}") + + num_res = len(res_idxs) + # check whether idxs are continuous: + if not np.array_equal(res_idxs, np.arange(num_res)+1): + return True + else: + return False + +def dist_breaks(chain_feats:dict, max_ca_ca_distance=4.5): + ''' + Returns the indices of the residues where the ca-ca distance is greater than max_ca_ca_distance + ''' + # check ca_ca distance: + xyz = chain_feats['trans_1'] + if isinstance(xyz, torch.Tensor): + xyz = xyz.detach().cpu().numpy() + elif isinstance(xyz, list): + xyz = np.array(xyz) + elif not isinstance(xyz, np.ndarray): + raise ValueError(f"xyz must be a torch.Tensor, list or np.ndarray, not {type(xyz)}") + + # calculate distances between subsequent CA atoms: + subsequent_dists = np.linalg.norm(xyz[1:] - xyz[:-1], axis=1) + return np.where(subsequent_dists >= max_ca_ca_distance)[0] + +def idx_breaks(chain_feats:dict): + ''' + Returns the indices of the residues where the res_idx is not continuous + ''' + res_idxs = chain_feats['res_idx'] + if isinstance(res_idxs, torch.Tensor): + res_idxs = res_idxs.detach().cpu().numpy() + elif isinstance(res_idxs, list): + res_idxs = np.array(res_idxs) + elif not isinstance(res_idxs, np.ndarray): + raise ValueError(f"res_idxs must be a torch.Tensor, list or np.ndarray, not {type(res_idxs)}") + + return np.where(res_idxs[1:] - np.roll(res_idxs, 1)[1:] != 1)[0] + + +def get_processed_feats(path, extra_feats:List[str]=None): + """ + Reads the processed features from a file. The file can be either a pickle or npz file. + """ + path_extension = Path(path).suffix + + if path_extension in PICKLE_EXTENSIONS: + processed_feats = read_pkl(path) + processed_feats = parse_chain_feats(processed_feats) + + elif path_extension == '.npz': + npz_dict = dict(np.load(path)) + biotite_struct = read_npz(npz_dict) + processed_feats = parse_npz_feats(npz_feats=biotite_struct) + processed_feats['modeled_idx'] = processed_feats['residue_index'] + if extra_feats is not None: + num_bb_atoms = processed_feats['atom_positions'].shape[0] + for k in npz_dict.keys(): + if k not in processed_feats.keys() and k in extra_feats: + + # check shape: + if npz_dict[k].shape[0] == 3*num_bb_atoms: + # only use every third atom: + npz_dict[k] = npz_dict[k][::3] + warnings.warn(f"Shape of {k} was 3 times the atom_positions shape, using every third atom") + elif npz_dict[k].shape[0] != num_bb_atoms: + raise ValueError(f"Shape of {k} does not match atom_positions shape") + + processed_feats[k] = npz_dict[k] + else: + raise ValueError(f'Unknown file extension {path_extension}') + + + + return processed_feats diff --git a/gafl/gafl/experiment_utils.py b/gafl/gafl/experiment_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..245bb8613ac4daf14a83d57ba0a18a3875224062 --- /dev/null +++ b/gafl/gafl/experiment_utils.py @@ -0,0 +1,213 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Utility functions for experiments.""" +import logging +import torch +import os +import numpy as np +from pytorch_lightning.utilities.rank_zero import rank_zero_only +from pytorch_lightning.callbacks import ModelCheckpoint +from typing_extensions import override, Optional +import json +from pathlib import Path +import pandas as pd +import collections + +from gafl.analysis import utils as au + +# Custom callback +from pytorch_lightning.callbacks import Callback + +class ValidationCallback(Callback): + + def __init__(self, first_epoch=0): + self.first_epoch = first_epoch + + def on_train_epoch_start(self, trainer, pl_module): + if pl_module.current_epoch < self.first_epoch: + trainer.limit_val_batches = 0 + else: + trainer.limit_val_batches = 1.0 + +class LengthDataset(torch.utils.data.Dataset): + def __init__(self, samples_cfg): + self._samples_cfg = samples_cfg + all_sample_lengths = range( + self._samples_cfg.min_length, + self._samples_cfg.max_length+1, + self._samples_cfg.length_step + ) + if samples_cfg.length_subset is not None: + all_sample_lengths = [ + int(x) for x in samples_cfg.length_subset + ] + all_sample_ids = [] + for length in all_sample_lengths: + for sample_id in range(self._samples_cfg.samples_per_length): + all_sample_ids.append((length, sample_id)) + self._all_sample_ids = all_sample_ids + + def __len__(self): + return len(self._all_sample_ids) + + def __getitem__(self, idx): + num_res, sample_id = self._all_sample_ids[idx] + batch = { + 'num_res': num_res, + 'sample_id': sample_id, + } + return batch + +class LengthDatasetBatch(torch.utils.data.Dataset): + def __init__(self, samples_cfg): + self._samples_cfg = samples_cfg + all_sample_lengths = range( + self._samples_cfg.min_length, + self._samples_cfg.max_length+1, + self._samples_cfg.length_step + ) + if samples_cfg.length_subset is not None: + all_sample_lengths = [ + int(x) for x in samples_cfg.length_subset + ] + all_sample_ids = [] + for length in all_sample_lengths: + all_sample_ids.append((length, np.arange(self._samples_cfg.samples_per_length))) + + self._all_sample_ids = all_sample_ids + + def __len__(self): + return len(self._all_sample_ids) + + def __getitem__(self, idx): + num_res, sample_id = self._all_sample_ids[idx] + batch = { + 'num_res': num_res, + 'sample_id': sample_id, + } + return batch + +def save_traj( + sample: np.ndarray, + bb_prot_traj: np.ndarray, + x0_traj: np.ndarray, + diffuse_mask: np.ndarray, + output_dir: str, + aatype = None, + ): + """Writes final sample and reverse diffusion trajectory. + + Args: + bb_prot_traj: [T, N, 37, 3] atom37 sampled diffusion states. + T is number of time steps. First time step is t=eps, + i.e. bb_prot_traj[0] is the final sample after reverse diffusion. + N is number of residues. + x0_traj: [T, N, 3] x_0 predictions of C-alpha at each time step. + aatype: [T, N, 21] amino acid probability vector trajectory. + res_mask: [N] residue mask. + diffuse_mask: [N] which residues are diffused. + output_dir: where to save samples. + + Returns: + Dictionary with paths to saved samples. + 'sample_path': PDB file of final state of reverse trajectory. + 'traj_path': PDB file os all intermediate diffused states. + 'x0_traj_path': PDB file of C-alpha x_0 predictions at each state. + b_factors are set to 100 for diffused residues and 0 for motif + residues if there are any. + """ + + # Write sample. + diffuse_mask = diffuse_mask.astype(bool) + sample_path = os.path.join(output_dir, 'sample.pdb') + prot_traj_path = os.path.join(output_dir, 'bb_traj.pdb') + x0_traj_path = os.path.join(output_dir, 'x0_traj.pdb') + + # Use b-factors to specify which residues are diffused. + b_factors = np.tile((diffuse_mask * 100)[:, None], (1, 37)) + + sample_path = au.write_prot_to_pdb( + sample, + sample_path, + b_factors=b_factors, + no_indexing=True, + aatype=aatype, + ) + prot_traj_path = au.write_prot_to_pdb( + bb_prot_traj, + prot_traj_path, + b_factors=b_factors, + no_indexing=True, + aatype=aatype, + ) + x0_traj_path = au.write_prot_to_pdb( + x0_traj, + x0_traj_path, + b_factors=b_factors, + no_indexing=True, + aatype=aatype + ) + return { + 'sample_path': sample_path, + 'traj_path': prot_traj_path, + 'x0_traj_path': x0_traj_path, + } + + +def get_pylogger(name=__name__) -> logging.Logger: + """Initializes multi-GPU-friendly python command line logger.""" + + logger = logging.getLogger(name) + + # this ensures all logging levels get marked with the rank zero decorator + # otherwise logs would get multiplied for each GPU process in multi-GPU setup + logging_levels = ("debug", "info", "warning", "error", "exception", "fatal", "critical") + for level in logging_levels: + setattr(logger, level, rank_zero_only(getattr(logger, level))) + + return logger + + +def flatten_dict(raw_dict): + """Flattens a nested dict.""" + flattened = [] + for k, v in raw_dict.items(): + if isinstance(v, dict): + flattened.extend([ + (f'{k}:{i}', j) for i, j in flatten_dict(v) + ]) + else: + flattened.append((k, v)) + return flattened + + +class EpochModelCheckpoint(ModelCheckpoint): + def __init__(self, first_epoch=0, **kwargs): + """ + Checkpoint that gets active only after a certain epoch. + """ + super().__init__(**kwargs) + self.first_epoch = first_epoch + + @override + def on_validation_end(self, trainer, pl_module): + if trainer.current_epoch >= self.first_epoch: + return super().on_validation_end(trainer, pl_module) + + @override + def on_train_epoch_end(self, trainer, pl_module): + if trainer.current_epoch >= self.first_epoch: + return super().on_train_epoch_end(trainer, pl_module) + + @override + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): + if trainer.current_epoch >= self.first_epoch: + return super().on_train_batch_end(trainer, pl_module, outputs, batch, batch_idx) + + def format_checkpoint_name(self, metrics, ver: Optional[int] = None): + """Overrides the filename formatting to remove specific prefixes from metric names.""" + # Reformat the metric names by removing 'valid/' prefix + metrics = {key.replace('valid/', ''): val for key, val in metrics.items()} + return super().format_checkpoint_name(metrics, ver) diff --git a/gafl/gafl/models/__init__.py b/gafl/gafl/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/gafl/models/__pycache__/__init__.cpython-310.pyc b/gafl/gafl/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03d58be244b1e6ba8173cb204f98c8f2065d9cd0 Binary files /dev/null and b/gafl/gafl/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/__init__.cpython-311.pyc b/gafl/gafl/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1dcf3dbfde8d8bd1e952506a512f784da2d4e9f Binary files /dev/null and b/gafl/gafl/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/edge_embedder.cpython-310.pyc b/gafl/gafl/models/__pycache__/edge_embedder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa40448730a0c483348962daebcb4ece2ce650f5 Binary files /dev/null and b/gafl/gafl/models/__pycache__/edge_embedder.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/edge_embedder.cpython-311.pyc b/gafl/gafl/models/__pycache__/edge_embedder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d020e26a96f19991c2f9218f436a305deb135e7b Binary files /dev/null and b/gafl/gafl/models/__pycache__/edge_embedder.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/flow_model.cpython-310.pyc b/gafl/gafl/models/__pycache__/flow_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..079a769856af6b826a16a2b28b2125c60e852a63 Binary files /dev/null and b/gafl/gafl/models/__pycache__/flow_model.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/flow_model.cpython-311.pyc b/gafl/gafl/models/__pycache__/flow_model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f5370ffaab1a2075f8cefc277eb789306507857 Binary files /dev/null and b/gafl/gafl/models/__pycache__/flow_model.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/flow_module.cpython-310.pyc b/gafl/gafl/models/__pycache__/flow_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d436c643b247f6ef1395501838cf196a267812b Binary files /dev/null and b/gafl/gafl/models/__pycache__/flow_module.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/flow_module.cpython-311.pyc b/gafl/gafl/models/__pycache__/flow_module.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d7f786dcd0170bcb2832c07c6b635d3a817495d Binary files /dev/null and b/gafl/gafl/models/__pycache__/flow_module.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-310.pyc b/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeb6aecf2c2c94c82f480a96846d6917e65251f5 Binary files /dev/null and b/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-311.pyc b/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9932da5953e0e278d13b4ecb42c9505c5aa3a2b Binary files /dev/null and b/gafl/gafl/models/__pycache__/ipa_pytorch.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/node_embedder.cpython-310.pyc b/gafl/gafl/models/__pycache__/node_embedder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d860967c12d5c0410fb656a12f51d7b77958e99 Binary files /dev/null and b/gafl/gafl/models/__pycache__/node_embedder.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/node_embedder.cpython-311.pyc b/gafl/gafl/models/__pycache__/node_embedder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d34430b3137f55aecc7e5cf3366b5f421de0830 Binary files /dev/null and b/gafl/gafl/models/__pycache__/node_embedder.cpython-311.pyc differ diff --git a/gafl/gafl/models/__pycache__/utils.cpython-310.pyc b/gafl/gafl/models/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fb091bedeedf7d97effedc4f5a2f06f0c1868b6 Binary files /dev/null and b/gafl/gafl/models/__pycache__/utils.cpython-310.pyc differ diff --git a/gafl/gafl/models/__pycache__/utils.cpython-311.pyc b/gafl/gafl/models/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9ad6ccd0cabf834e14909dbcfbef77447a7ccb6 Binary files /dev/null and b/gafl/gafl/models/__pycache__/utils.cpython-311.pyc differ diff --git a/gafl/gafl/models/edge_embedder.py b/gafl/gafl/models/edge_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..8561e7242d3dca93c47a096cc44d69d24aae6ceb --- /dev/null +++ b/gafl/gafl/models/edge_embedder.py @@ -0,0 +1,97 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import torch +from torch import nn + +from gafl.models.utils import get_index_embedding, calc_distogram + +class EdgeEmbedder(nn.Module): + + def __init__(self, module_cfg): + super(EdgeEmbedder, self).__init__() + self._cfg = module_cfg + + if "permutation_equivariance" in self._cfg: + self.permutation_equivariance = self._cfg.permutation_equivariance + else: + self.permutation_equivariance = False + + if "embed_breaks" in self._cfg: + self.embed_breaks = self._cfg.embed_breaks + else: + self.embed_breaks = False + + if self.embed_breaks: + self.c_breaks = 2 + else: + self.c_breaks = 0 + + self.c_s = self._cfg.c_s + self.c_p = self._cfg.c_p + self.feat_dim = self._cfg.feat_dim + + self.linear_s_p = nn.Linear(self.c_s, self.feat_dim) + self.linear_relpos = nn.Linear(self.feat_dim, self.feat_dim) + + total_edge_feats = self.feat_dim * 3 + self._cfg.num_bins * 2 + self.edge_embedder = nn.Sequential( + nn.Linear(total_edge_feats, self.c_p), + nn.ReLU(), + nn.Linear(self.c_p, self.c_p), + nn.ReLU(), + nn.Linear(self.c_p, self.c_p), + nn.LayerNorm(self.c_p), + ) + + def embed_relpos(self, pos, breaks=None): + rel_pos = pos[:, :, None] - pos[:, None, :] + pos_emb = get_index_embedding(rel_pos, self._cfg.feat_dim - self.c_breaks, max_len=2056) + + # Adding breaks here enables to keep the same feat_dim and thus the same parameter set as without breaks thus making both models backwards compatible + if self.embed_breaks: + if breaks is None: + breaks = torch.zeros([pos.shape[0], pos.shape[1], pos.shape[1]], device=pos.device, dtype=torch.float32) + else: + breaks = breaks[:, :, None] * breaks[:, None, :] * (torch.diag(torch.ones(pos.shape[1] - 1, device=pos.device, dtype=torch.float32), diagonal=1) + torch.diag(torch.ones(pos.shape[1] - 1, device=pos.device, dtype=torch.float32), diagonal=-1)).unsqueeze(0) + + pos_emb = torch.cat([pos_emb, breaks.unsqueeze(-1), (1 - breaks).unsqueeze(-1)], dim=-1) + + return self.linear_relpos(pos_emb) + + def _cross_concat(self, feats_1d, num_batch, num_res): + return torch.cat([ + torch.tile(feats_1d[:, :, None, :], (1, 1, num_res, 1)), + torch.tile(feats_1d[:, None, :, :], (1, num_res, 1, 1)), + ], dim=-1).float().reshape([num_batch, num_res, num_res, -1]) + + def forward(self, s, t, sc_t, p_mask, res_idx=None, breaks=None): + num_batch, num_res, _ = s.shape + p_i = self.linear_s_p(s) + cross_node_feats = self._cross_concat(p_i, num_batch, num_res) + if res_idx is None: + pos = torch.arange( + num_res, device=s.device).unsqueeze(0).repeat(num_batch, 1) + else: + pos = res_idx.float() + + if self.permutation_equivariance: + # NOTE: remove positional encoding, except for first and last residue + pos[:, 1:-1] = torch.ones_like(pos[:, 1:-1]) + # set the first residue to 0 and the last to 2, then multiply by half of max len + pos[:, 0] = 0 + pos[:, -1] = 2 + pos = pos * 1028 + + relpos_feats = self.embed_relpos(pos, breaks=breaks) + + dist_feats = calc_distogram( + t, min_bin=1e-3, max_bin=20.0, num_bins=self._cfg.num_bins) + sc_feats = calc_distogram( + sc_t, min_bin=1e-3, max_bin=20.0, num_bins=self._cfg.num_bins) + + all_edge_feats = torch.concat([cross_node_feats, relpos_feats, dist_feats, sc_feats], dim=-1) + edge_feats = self.edge_embedder(all_edge_feats) + edge_feats *= p_mask.unsqueeze(-1) + return edge_feats \ No newline at end of file diff --git a/gafl/gafl/models/flow_model.py b/gafl/gafl/models/flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..47d2a97bd98dc5ee44a379ab81f0f56d5bafac05 --- /dev/null +++ b/gafl/gafl/models/flow_model.py @@ -0,0 +1,122 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Neural network architecture for the flow model.""" +import torch +from torch import nn + +from gafl.models.node_embedder import NodeEmbedder +from gafl.models.edge_embedder import EdgeEmbedder +from gafl.models import ipa_pytorch +from gafl.data import utils as du + + +class FlowModel(nn.Module): + + def __init__(self, model_conf): + super(FlowModel, self).__init__() + self._model_conf = model_conf + self._ipa_conf = model_conf.ipa + self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE) + self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE) + self.node_embedder = NodeEmbedder(model_conf.node_features) + self.edge_embedder = EdgeEmbedder(model_conf.edge_features) + + # Attention trunk + self.trunk = nn.ModuleDict() + for b in range(self._ipa_conf.num_blocks): + self.trunk[f'ipa_{b}'] = ipa_pytorch.InvariantPointAttention(self._ipa_conf) + self.trunk[f'ipa_ln_{b}'] = nn.LayerNorm(self._ipa_conf.c_s) + tfmr_in = self._ipa_conf.c_s + tfmr_layer = torch.nn.TransformerEncoderLayer( + d_model=tfmr_in, + nhead=self._ipa_conf.seq_tfmr_num_heads, + dim_feedforward=tfmr_in, + batch_first=True, + dropout=0.0, + norm_first=False + ) + self.trunk[f'seq_tfmr_{b}'] = torch.nn.TransformerEncoder( + tfmr_layer, self._ipa_conf.seq_tfmr_num_layers, enable_nested_tensor=False) + self.trunk[f'post_tfmr_{b}'] = ipa_pytorch.Linear( + tfmr_in, self._ipa_conf.c_s, init="final") + self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition( + c=self._ipa_conf.c_s) + self.trunk[f'bb_update_{b}'] = ipa_pytorch.BackboneUpdate( + self._ipa_conf.c_s, use_rot_updates=True) + + if b < self._ipa_conf.num_blocks-1: + # No edge update on the last block. + edge_in = self._model_conf.edge_embed_size + self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition( + node_embed_size=self._ipa_conf.c_s, + edge_embed_in=edge_in, + edge_embed_out=self._model_conf.edge_embed_size, + ) + + def forward(self, input_feats): + # During sampling res_idx is not provided + if 'res_idx' not in input_feats: + res_idx = None + else: + res_idx = input_feats['res_idx'] + + if 'breaks' in input_feats: + breaks = input_feats['breaks'] + else: + breaks = None + + node_mask = input_feats['res_mask'] + edge_mask = node_mask[:, None] * node_mask[:, :, None] + continuous_t = input_feats['t'] + trans_t = input_feats['trans_t'] + rotmats_t = input_feats['rotmats_t'] + + # Initialize node and edge embeddings + init_node_embed = self.node_embedder(continuous_t, node_mask, res_idx=res_idx, breaks=breaks) + if 'trans_sc' not in input_feats: + trans_sc = torch.zeros_like(trans_t) + else: + trans_sc = input_feats['trans_sc'] + init_edge_embed = self.edge_embedder( + init_node_embed, trans_t, trans_sc, edge_mask, res_idx=res_idx, breaks=breaks) + + # Initial rigids + curr_rigids = du.create_rigid(rotmats_t, trans_t,) + + # Main trunk + curr_rigids = self.rigids_ang_to_nm(curr_rigids) + init_node_embed = init_node_embed * node_mask[..., None] + node_embed = init_node_embed * node_mask[..., None] + edge_embed = init_edge_embed * edge_mask[..., None] + for b in range(self._ipa_conf.num_blocks): + ipa_embed = self.trunk[f'ipa_{b}']( + node_embed, + edge_embed, + curr_rigids, + node_mask) + ipa_embed *= node_mask[..., None] + node_embed = self.trunk[f'ipa_ln_{b}'](node_embed + ipa_embed) + seq_tfmr_out = self.trunk[f'seq_tfmr_{b}']( + node_embed, src_key_padding_mask=(1 - node_mask).bool()) + node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out) + node_embed = self.trunk[f'node_transition_{b}'](node_embed) + node_embed = node_embed * node_mask[..., None] + rigid_update = self.trunk[f'bb_update_{b}']( + node_embed * node_mask[..., None]) + curr_rigids = curr_rigids.compose_q_update_vec( + rigid_update, node_mask[..., None]) + + if b < self._ipa_conf.num_blocks-1: + edge_embed = self.trunk[f'edge_transition_{b}']( + node_embed, edge_embed) + edge_embed *= edge_mask[..., None] + + curr_rigids = self.rigids_nm_to_ang(curr_rigids) + pred_trans = curr_rigids.get_trans() + pred_rotmats = curr_rigids.get_rots().get_rot_mats() + return { + 'pred_trans': pred_trans, + 'pred_rotmats': pred_rotmats, + } diff --git a/gafl/gafl/models/flow_module.py b/gafl/gafl/models/flow_module.py new file mode 100644 index 0000000000000000000000000000000000000000..948785915b803e547cd153387649d52eaade1d92 --- /dev/null +++ b/gafl/gafl/models/flow_module.py @@ -0,0 +1,606 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from typing import Any +import torch +import time +import os +import random +import wandb +import math +import numpy as np +import pandas as pd +import logging +from pytorch_lightning import LightningModule +from pytorch_lightning.loggers.wandb import WandbLogger +import torch.distributed as dist +import shutil +from omegaconf import OmegaConf +import warnings + +from gafl.analysis import metrics +from gafl.analysis import utils as au +from gafl.models.flow_model import FlowModel +from gafl.models import utils as mu +from gafl.data.interpolant import Interpolant +from gafl.data import utils as du +from gafl.data import all_atom +from gafl.data import so3_utils +from gafl.data import residue_constants +from gafl.data.protein import from_pdb_string +from gafl import experiment_utils as eu +# Suppress only the specific PyTorch Lightning user warnings about sync_dist, which are triggered although the world size is 1. +warnings.filterwarnings("ignore", message=".*sync_dist=True.*") + +class FlowModule(LightningModule): + + def __init__(self, cfg, folding_cfg=None): + super().__init__() + self._print_logger = logging.getLogger(__name__) + self._exp_cfg = cfg.experiment + self._model_cfg = cfg.model + self._data_cfg = cfg.data + self._interpolant_cfg = cfg.interpolant + + # Set-up vector field prediction model and interpolant + self.create_model() + + self._sample_write_dir = self._exp_cfg.checkpointer.dirpath + os.makedirs(self._sample_write_dir, exist_ok=True) + + self.training_epoch_metrics = [] + + self.validation_epoch_metrics = [] + self.validation_sample_epoch_metrics = [] + self.validation_epoch_samples = [] + + self._time_bins = torch.linspace(0.0, 1.0, 101) + self._time_histogram = torch.zeros(100, dtype=torch.int64) + + self.nan_steps = 0 + + if hasattr(self._exp_cfg, 'warmup_lr'): + self.warmup_lr = self._exp_cfg.warmup_lr + else: + self.warmup_lr = False + + if hasattr(self._exp_cfg, 'warmup_lr_factor'): + self.warmup_lr_factor = self._exp_cfg.warmup_lr_factor + else: + self.warmup_lr_factor = 0.1 + + OmegaConf.set_struct(self._exp_cfg, False) + if not hasattr(self._exp_cfg, 'scheduler'): + self._exp_cfg.scheduler = OmegaConf.create() + self._exp_cfg.scheduler.enabled=False + OmegaConf.set_struct(self._exp_cfg, True) + + if hasattr(self._exp_cfg, 'reset_optimizer_on_load'): + self.reset_optimizer_on_load = self._exp_cfg.reset_optimizer_on_load + else: + self.reset_optimizer_on_load = False + + self.save_hyperparameters() + + def create_model(self): + if "module" in self._model_cfg: + # backwards compatibility: + if 'gafl_pdb_new' in self._model_cfg.module: + self._model_cfg.module = str(self._model_cfg.module).replace('gafl_pdb_new', 'flow_model') + model_module = mu.load_module(self._model_cfg.module) + self.model = model_module(self._model_cfg) + else: + self.model = FlowModel(self._model_cfg) + self.interpolant = Interpolant(self._interpolant_cfg) + + def on_train_start(self): + self._epoch_start_time = time.time() + + def on_train_epoch_end(self): + if not self.training_epoch_metrics: + logging.warning('No training metrics to log') + self.training_epoch_metrics.clear() + self._epoch_start_time = time.time() + return + + train_epoch_metrics = pd.concat(self.training_epoch_metrics) + + train_epoch_dict = train_epoch_metrics.mean().to_dict() + + for metric_name,metric_val in train_epoch_dict.items(): + self._log_scalar( + f'train_epoch/{metric_name}', + metric_val, + on_step=False, + on_epoch=True, + prog_bar=False, + batch_size=len(train_epoch_metrics), + ) + + self.training_epoch_metrics.clear() + + epoch_time = (time.time() - self._epoch_start_time) / 60.0 + self._log_scalar( + 'train/epoch_time_minutes', + epoch_time, + on_step=False, + on_epoch=True, + prog_bar=False + ) + self._epoch_start_time = time.time() + + def loss_fn(self, noisy_batch: Any, model_output: Any): + training_cfg = self._exp_cfg.training + loss_mask = noisy_batch['res_mask'] + if training_cfg.min_plddt_mask is not None: + plddt_mask = noisy_batch['res_plddt'] > training_cfg.min_plddt_mask + loss_mask *= plddt_mask + num_batch, num_res = loss_mask.shape + + # Ground truth labels + gt_trans_1 = noisy_batch['trans_1'] + gt_rotmats_1 = noisy_batch['rotmats_1'] + rotmats_t = noisy_batch['rotmats_t'] + # autocast re-casts the matmuls inside calc_rot_vf to bf16 no matter what + # dtype is passed in, so disabling it is the part that matters; the casts + # only guarantee the inputs. + with torch.autocast(device_type=rotmats_t.device.type, enabled=False): + gt_rot_vf = so3_utils.calc_rot_vf( + rotmats_t.type(torch.float32), gt_rotmats_1.type(torch.float32)) + gt_bb_atoms = all_atom.to_atom37(gt_trans_1, gt_rotmats_1)[:, :, :3] + + # Timestep used for normalization. + t = noisy_batch['t'] + norm_scale = 1 - torch.min( + t[..., None], torch.tensor(training_cfg.t_normalize_clip)) + + # Model output predictions. + pred_trans_1 = model_output['pred_trans'] + pred_rotmats_1 = model_output['pred_rotmats'] + # calc_rot_vf is the SO(3) log map: arccos((tr(R)-1)/2) with a 1/sin(theta) + # in its backward, which goes non-finite under bf16's 8-bit mantissa even + # where the forward value is fine. The gt path above was already cast to + # float32; this is the path that carries gradients. + # This is the path that carries gradients. calc_rot_vf is the SO(3) log + # map: d/dx arccos(x) = -1/sqrt(1-x^2) diverges as the relative rotation + # approaches 0 or pi, and bf16's 8-bit mantissa rounds x to exactly +-1 + # there. The forward value stays finite; the backward does not. Verified + # by scripts/cmfm_replay_failure.py: rots_vf_loss produced 534 non-finite + # parameter grads in bf16 and zero in fp32 on the same microbatch. + with torch.autocast(device_type=rotmats_t.device.type, enabled=False): + pred_rots_vf = so3_utils.calc_rot_vf( + rotmats_t.type(torch.float32), pred_rotmats_1.type(torch.float32)) + + # Backbone atom loss + pred_bb_atoms = all_atom.to_atom37(pred_trans_1, pred_rotmats_1)[:, :, :3] + gt_bb_atoms *= training_cfg.bb_atom_scale / norm_scale[..., None] + pred_bb_atoms *= training_cfg.bb_atom_scale / norm_scale[..., None] + loss_denom = torch.sum(loss_mask, dim=-1) * 3 + # loss denom may not contain any zeros: + assert (loss_denom == 0).sum() == 0, 'Loss denom contains zeros' + + bb_atom_loss = torch.sum( + (gt_bb_atoms - pred_bb_atoms) ** 2 * loss_mask[..., None, None], + dim=(-1, -2, -3) + ) / loss_denom + + # Translation VF loss + trans_error = (gt_trans_1 - pred_trans_1) / norm_scale * training_cfg.trans_scale + trans_loss = training_cfg.translation_loss_weight * torch.sum( + trans_error ** 2 * loss_mask[..., None], + dim=(-1, -2) + ) / loss_denom + + # Rotation VF loss + rots_vf_error = (gt_rot_vf - pred_rots_vf) / norm_scale + rots_vf_loss = training_cfg.rotation_loss_weights * torch.sum( + rots_vf_error ** 2 * loss_mask[..., None], + dim=(-1, -2) + ) / loss_denom + + # Pairwise distance loss + gt_flat_atoms = gt_bb_atoms.reshape([num_batch, num_res*3, 3]) + gt_pair_dists = torch.linalg.norm( + gt_flat_atoms[:, :, None, :] - gt_flat_atoms[:, None, :, :], dim=-1) + pred_flat_atoms = pred_bb_atoms.reshape([num_batch, num_res*3, 3]) + pred_pair_dists = torch.linalg.norm( + pred_flat_atoms[:, :, None, :] - pred_flat_atoms[:, None, :, :], dim=-1) + + flat_loss_mask = torch.tile(loss_mask[:, :, None], (1, 1, 3)) + flat_loss_mask = flat_loss_mask.reshape([num_batch, num_res*3]) + flat_res_mask = torch.tile(loss_mask[:, :, None], (1, 1, 3)) + flat_res_mask = flat_res_mask.reshape([num_batch, num_res*3]) + + gt_pair_dists = gt_pair_dists * flat_loss_mask[..., None] + pred_pair_dists = pred_pair_dists * flat_loss_mask[..., None] + pair_dist_mask = flat_loss_mask[..., None] * flat_res_mask[:, None, :] + + dist_mat_loss = torch.sum( + (gt_pair_dists - pred_pair_dists)**2 * pair_dist_mask, + dim=(1, 2)) + dist_mat_loss /= (torch.sum(pair_dist_mask, dim=(1, 2)) - num_res) + + se3_vf_loss = trans_loss + rots_vf_loss + auxiliary_loss = (bb_atom_loss + dist_mat_loss) * ( + t[:, 0] > training_cfg.aux_loss_t_pass + ) + auxiliary_loss *= self._exp_cfg.training.aux_loss_weight + se3_vf_loss += auxiliary_loss + # if torch.isnan(se3_vf_loss).any(): + # raise ValueError('NaN loss encountered') + return { + "bb_atom_loss": bb_atom_loss, + "trans_loss": trans_loss, + "dist_mat_loss": dist_mat_loss, + "auxiliary_loss": auxiliary_loss, + "rots_vf_loss": rots_vf_loss, + "se3_vf_loss": se3_vf_loss + } + + def model_step(self, noisy_batch: Any): + model_output = self.model(noisy_batch) + + losses = self.loss_fn(noisy_batch, model_output) + return losses + + def validation_step(self, batch: Any, batch_idx: int, dataloader_idx=0): + if batch is None: + return + + if dataloader_idx == 0: + res_mask = batch['res_mask'] + self.interpolant.set_device(res_mask.device) + num_batch, num_res = res_mask.shape + + samples = self.interpolant.sample( + num_batch, + num_res, + self.model, + )[0][-1].numpy() + + batch_metrics = [] + for i in range(num_batch): + + # Write out sample to PDB file + final_pos = samples[i] + saved_path = au.write_prot_to_pdb( + final_pos, + os.path.join( + self._sample_write_dir, + f'sample_{i}_idx_{batch_idx}_len_{num_res}.pdb'), + no_indexing=True + ) + if isinstance(self.logger, WandbLogger): + with open(saved_path, 'r') as f: + atom37 = from_pdb_string(f.read()).atom_positions + N = atom37.shape[0] + backbone = atom37[:,:5,:] + colors = np.zeros((N, 5, 3)) + colors[:,0,:] = np.array([0.0, 0.0, 1.0]) + colors[:,1,:] = np.array([0.25, 0.75, 0.75]) + colors[:,2,:] = np.array([0.25, 0.75, 0.75]) + colors[:,3,:] = np.array([0.25, 0.75, 0.75]) + colors[:,4,:] = np.array([1.0, 0.0, 0.0]) + backbone = np.concatenate([backbone, colors*255], axis=-1).reshape(N*5, 6) + Ca_atoms = atom37[:,1,:] + self.validation_epoch_samples.append( + [saved_path, self.global_step, wandb.Molecule(saved_path), wandb.Object3D(backbone), wandb.Object3D(Ca_atoms)] + ) + + mdtraj_metrics = metrics.calc_mdtraj_metrics(saved_path) + ca_idx = residue_constants.atom_order['CA'] + ca_ca_metrics = metrics.calc_ca_ca_metrics(final_pos[:, ca_idx]) + batch_metrics.append((mdtraj_metrics | ca_ca_metrics)) + + batch_metrics = pd.DataFrame(batch_metrics) + self.validation_sample_epoch_metrics.append(batch_metrics) + + if batch_idx == 0: + self.target_helix_percent = batch['target_helix_percent'] + self.target_strand_percent = batch['target_strand_percent'] + + if dataloader_idx == 1: + self.interpolant.set_device(batch['res_mask'].device) + noisy_batch = self.interpolant.corrupt_batch(batch) + if self._interpolant_cfg.self_condition and random.random() > 0.5: + with torch.no_grad(): + model_sc = self.model(noisy_batch) + noisy_batch['trans_sc'] = model_sc['pred_trans'] + batch_losses = self.model_step(noisy_batch) + + batch_metrics = {} + batch_metrics.update({k: [torch.mean(v).cpu().item()] for k,v in batch_losses.items()}) + + # Losses to track. Stratified across t. + t = torch.squeeze(noisy_batch['t']) + + if self._exp_cfg.training.t_bins > 1: + for loss_name, loss_dict in batch_losses.items(): + stratified_losses = mu.t_stratified_loss( + t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name) + batch_metrics.update({k: [v] for k,v in stratified_losses.items()}) + + batch_metrics = pd.DataFrame(batch_metrics) + self.validation_epoch_metrics.append(batch_metrics) + + + def on_validation_epoch_end(self): + if len(self.validation_epoch_samples) > 0: + self.logger.log_table( + key='valid/samples', + columns=["sample_path", "global_step", "Protein", "Backbone", "C-alpha"], + data=self.validation_epoch_samples) + self.validation_epoch_samples.clear() + + if len(self.validation_sample_epoch_metrics) > 0: + val_epoch_metrics = pd.concat(self.validation_sample_epoch_metrics) + + val_epoch_dict = val_epoch_metrics.mean().to_dict() + # Calculate deviation of mean helix percent and mean strand percent from dataset + # this quantity is actually the mean of the mean of the residue-level helix and strand percent! (which is fine, otherwise small proteins would have less weight) + helix_deviation = val_epoch_metrics['helix_percent'].mean() - self.target_helix_percent + strand_deviation = val_epoch_metrics['strand_percent'].mean() - self.target_strand_percent + # sec_deviation = math.sqrt(helix_deviation**2 + strand_deviation**2) + sec_deviation = abs(helix_deviation) + abs(strand_deviation) + self._log_scalar( + 'valid/sec_deviation', + sec_deviation, + on_step=False, + on_epoch=True, + prog_bar=False, + batch_size=len(val_epoch_metrics) + ) + + for metric_name,metric_val in val_epoch_dict.items(): + self._log_scalar( + f'valid/{metric_name}', + metric_val, + on_step=False, + on_epoch=True, + prog_bar=False, + batch_size=len(val_epoch_metrics), + ) + self.validation_sample_epoch_metrics.clear() + + + if len(self.validation_epoch_metrics) > 0: + val_epoch_metrics = pd.concat(self.validation_epoch_metrics) + + val_epoch_dict = val_epoch_metrics.mean().to_dict() + + for metric_name,metric_val in val_epoch_dict.items(): + self._log_scalar( + f'valid/{metric_name}', + metric_val, + on_step=False, + on_epoch=True, + prog_bar=False, + batch_size=len(val_epoch_metrics), + ) + + + self.validation_epoch_metrics.clear() + + def _log_scalar( + self, + key, + value, + on_step=True, + on_epoch=False, + prog_bar=True, + batch_size=None, + sync_dist=False, + rank_zero_only=True + ): + if sync_dist is None: + sync_dist = self.trainer.world_size > 1 + if rank_zero_only is None: + rank_zero_only = not sync_dist + if sync_dist and rank_zero_only: + raise ValueError('Unable to sync dist when rank_zero_only=True') + self.log( + key, + value, + on_step=on_step, + on_epoch=on_epoch, + prog_bar=prog_bar, + batch_size=batch_size, + sync_dist=sync_dist, + rank_zero_only=rank_zero_only + ) + + def training_step(self, batch: Any, stage: int): + batchsize = batch['res_mask'].shape[0] + step_start_time = time.time() + self.interpolant.set_device(batch['res_mask'].device) + noisy_batch = self.interpolant.corrupt_batch(batch) + if self._interpolant_cfg.self_condition and random.random() > 0.5: + with torch.no_grad(): + model_sc = self.model(noisy_batch) + noisy_batch['trans_sc'] = model_sc['pred_trans'] + batch_losses = self.model_step(noisy_batch) + num_batch = batch_losses['bb_atom_loss'].shape[0] + total_losses = { + k: torch.mean(v) for k,v in batch_losses.items() + } + + train_loss = ( + total_losses[self._exp_cfg.training.loss] + + total_losses['auxiliary_loss'] + ) + + nan_detected = torch.isnan(train_loss).float() + + # Ensure all processes are aware of NaNs + if self.trainer.world_size > 1: # Check if using DDP + dist.all_reduce(nan_detected, op=dist.ReduceOp.SUM) + + # If any process detected NaN, skip the step across all GPUs + if nan_detected > 0: + self.nan_steps += 1 + if self.nan_steps > 5: + raise ValueError('NaN loss encountered too many times in a row') + if self.global_rank == 0: + logging.info(f"NaN detected in loss (epoch {self.current_epoch}). Skipping this step.") + return None # Skip the step + else: + self.nan_steps = 0 + + for k,v in total_losses.items(): + self._log_scalar( + f"train/{k}", v, prog_bar=False, batch_size=num_batch) + + + batch_metrics = {} + batch_metrics.update({k: [v.cpu().item()] for k,v in total_losses.items()}) + + # Losses to track. Stratified across t. + t = torch.squeeze(noisy_batch['t']) + self._log_scalar( + "train/t", + np.mean(du.to_numpy(t)), + prog_bar=False, batch_size=num_batch) + + if self._exp_cfg.training.t_bins > 1: + for loss_name, loss_dict in batch_losses.items(): + stratified_losses = mu.t_stratified_loss( + t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name) + batch_metrics.update({k: [v] for k,v in stratified_losses.items()}) + + for k,v in stratified_losses.items(): + self._log_scalar( + f"train/{k}", v, prog_bar=False, batch_size=num_batch) + + batch_metrics = pd.DataFrame(batch_metrics) + self.training_epoch_metrics.append(batch_metrics) + + # Training throughput + self._log_scalar( + "train/length", float(batch['res_mask'].shape[1]), prog_bar=False, batch_size=num_batch) + self._log_scalar( + "train/batch_size", float(num_batch), prog_bar=False) + step_time = time.time() - step_start_time + self._log_scalar( + "train/examples_per_second", num_batch / step_time) + # train_loss = ( + # total_losses[self._exp_cfg.training.loss] + # + total_losses['auxiliary_loss'] + # ) # This double counts the auxiliary loss + # train_loss = total_losses[self._exp_cfg.training.loss] + self._log_scalar( + "train/loss", train_loss, batch_size=num_batch) + + if self._exp_cfg.use_wandb: + wandb_logs = {} + time_indices = torch.bucketize(noisy_batch["t"].detach().cpu(), self._time_bins) + time_indices_unique, counts = torch.unique(time_indices-1, return_counts=True) + time_indices_unique[time_indices_unique < 0] = 0 + self._time_histogram[time_indices_unique] += counts + wandb_logs["sampled_time_cumulative"] = wandb.Histogram( + np_histogram=(( + (self._time_histogram/self._time_histogram.sum()).numpy(), + self._time_bins.numpy() + )) + ) + time_histogram_step = torch.zeros(self._time_histogram.shape) + time_histogram_step[time_indices_unique] += counts + wandb_logs["sampled_time_per_step"] = wandb.Histogram( + np_histogram=(( + (time_histogram_step/time_histogram_step.sum()).numpy(), + self._time_bins.numpy() + )) + ) + self.logger.experiment.log(wandb_logs) + + + return train_loss + + def lr_lambda(self, epoch): + if epoch < self._exp_cfg.scheduler.warmup_epochs: + # Warmup phase: Linear increase + warmup_factor = epoch / self._exp_cfg.scheduler.warmup_epochs + return warmup_factor + (1 - warmup_factor) * self._exp_cfg.scheduler.warmup_lr / self._exp_cfg.optimizer.lr + elif epoch < self._exp_cfg.scheduler.warmup_epochs + self._exp_cfg.scheduler.constant_epochs: + # Constant LR phase + return 1.0 + elif epoch < self._exp_cfg.scheduler.min_epoch: + # Decay phase: Cosine annealing + decay_epochs = epoch - (self._exp_cfg.scheduler.warmup_epochs + self._exp_cfg.scheduler.constant_epochs) + decay_factor = 0.5 * (1 + math.cos(torch.pi * decay_epochs / (self._exp_cfg.scheduler.min_epoch - self._exp_cfg.scheduler.warmup_epochs - self._exp_cfg.scheduler.constant_epochs))) + return self._exp_cfg.scheduler.lr_min / self._exp_cfg.optimizer.lr * (1 - decay_factor) + decay_factor + else: + return self._exp_cfg.scheduler.lr_min / self._exp_cfg.optimizer.lr + + def configure_optimizers(self): + if not self._exp_cfg.scheduler.enabled: + return torch.optim.AdamW( + params=self.model.parameters(), + **self._exp_cfg.optimizer + ) + else: + optimizer = torch.optim.AdamW( + params=self.model.parameters(), + **self._exp_cfg.optimizer + ) + # if self.warmup_lr_factor == 0: + # return optimizer + + # # train the first epoch with a smaller learning rate: + # small_lr = self.warmup_lr_factor * self._exp_cfg.optimizer.lr + # this_epoch = self.trainer.current_epoch + + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, + lr_lambda=self.lr_lambda + ) + return [optimizer], [scheduler] + + def lr_scheduler_step(self, scheduler, *args, **kwargs): + scheduler.step() + + def on_load_checkpoint(self, *args, **kwargs): + output = super().on_load_checkpoint(*args, **kwargs) + if self.reset_optimizer_on_load: + self.configure_optimizers() + return output + + + def predict_step(self, batch, batch_idx): + device = f'cuda:{torch.cuda.current_device()}' + interpolant = Interpolant(self._infer_cfg.interpolant) + interpolant.set_device(device) + + sample_length = batch['num_res'].item() + diffuse_mask = torch.ones(1, sample_length) + all_sample_ids = batch['sample_id'][0].cpu().numpy() + + batch_size = self._infer_cfg.samples.batch_size + sample_ids_batches = np.split( + all_sample_ids, + np.arange(batch_size, len(all_sample_ids), batch_size) + ) + + for sample_ids in sample_ids_batches: + length_dir = os.path.join(self._output_dir, f'length_{sample_length}') + + for i, sample_id in enumerate(sample_ids): + sample_dir = os.path.join(length_dir, f'sample_{sample_id}') + os.makedirs(sample_dir, exist_ok=True) + + atom37_traj, model_traj, _ = interpolant.sample( + len(sample_ids), sample_length, self.model, save_path=length_dir + ) + + atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1)) + model_traj = du.to_numpy(torch.stack(model_traj, dim=1)) + + for i, sample_id in enumerate(sample_ids): + sample_dir = os.path.join(length_dir, f'sample_{sample_id}') + paths = eu.save_traj( + atom37_traj[i, -1], + np.flip(atom37_traj[i], axis=0), + np.flip(model_traj[i], axis=0), + du.to_numpy(diffuse_mask)[0], + output_dir=sample_dir, + ) \ No newline at end of file diff --git a/gafl/gafl/models/gafl/__init__.py b/gafl/gafl/models/gafl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/gafl/models/gafl/__pycache__/__init__.cpython-310.pyc b/gafl/gafl/models/gafl/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60fe7b1f4db1754284a76b204fa1a4233cc487d5 Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/__init__.cpython-310.pyc differ diff --git a/gafl/gafl/models/gafl/__pycache__/__init__.cpython-311.pyc b/gafl/gafl/models/gafl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c4561659c013a2d8f283ec9e1f51fdc0696d92f Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/__init__.cpython-311.pyc differ diff --git a/gafl/gafl/models/gafl/__pycache__/cfa.cpython-310.pyc b/gafl/gafl/models/gafl/__pycache__/cfa.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a01f6d550ab239b5935ec75afae3e84d91daf8f Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/cfa.cpython-310.pyc differ diff --git a/gafl/gafl/models/gafl/__pycache__/cfa.cpython-311.pyc b/gafl/gafl/models/gafl/__pycache__/cfa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d5abf2755a74c44f2f7d4d7b84c8fce37039a25 Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/cfa.cpython-311.pyc differ diff --git a/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-310.pyc b/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea77410efc2ad1554361b3e2003b6672db6782f8 Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-310.pyc differ diff --git a/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-311.pyc b/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3de84b2df0e927b33b3004b23c778b8a6eecb35c Binary files /dev/null and b/gafl/gafl/models/gafl/__pycache__/pga_utils.cpython-311.pyc differ diff --git a/gafl/gafl/models/gafl/cfa.py b/gafl/gafl/models/gafl/cfa.py new file mode 100644 index 0000000000000000000000000000000000000000..737dc4fa7af3a0d3202c9e67a0ca5962f9667024 --- /dev/null +++ b/gafl/gafl/models/gafl/cfa.py @@ -0,0 +1,599 @@ +# Based on the code for IPA in gafl/models/ipa_pytorch.py, which is licenced under: +# -------------------------------------------------------------------------- +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# -------------------------------------------------------------------------- + +# Applies to changes to the code for IPA as defined in gafl/models/ipa_pytorch.py: +# -------------------------------------------------------------------------- +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +# -------------------------------------------------------------------------- + + +"""Neural network architecture for the flow model.""" +import numpy as np +import torch +import math +from scipy.stats import truncnorm +import torch.nn as nn +from typing import Optional, Callable, List, Sequence + +from gatr.layers.linear import EquiLinear + +from gafl.data import all_atom +from gafl.models.gafl.pga_utils import extract_motor, embed_quat_frames, PairwiseGeometricBilinear, GMBCLayer, point_trafo, ga_norm, ga_versor, ga_inverse_versor, local_rel_trafo +from gafl.models.gafl import pga_utils as pu + + +def permute_final_dims(tensor: torch.Tensor, inds: List[int]): + zero_index = -1 * len(inds) + first_inds = list(range(len(tensor.shape[:zero_index]))) + return tensor.permute(first_inds + [zero_index + i for i in inds]) + + +def flatten_final_dims(t: torch.Tensor, no_dims: int): + return t.reshape(t.shape[:-no_dims] + (-1,)) + + +def gfa_point_weights_init_(weights): + with torch.no_grad(): + weights.fill_(-2.0) # This is an empirical value which has proven to work well in practice + +def _prod(nums): + out = 1 + for n in nums: + out = out * n + return out + +def _calculate_fan(linear_weight_shape, fan="fan_in"): + fan_out, fan_in = linear_weight_shape + + if fan == "fan_in": + f = fan_in + elif fan == "fan_out": + f = fan_out + elif fan == "fan_avg": + f = (fan_in + fan_out) / 2 + else: + raise ValueError("Invalid fan option") + + return f + +def trunc_normal_init_(weights, scale=1.0, fan="fan_in"): + shape = weights.shape + f = _calculate_fan(shape, fan) + scale = scale / max(1, f) + a = -2 + b = 2 + std = math.sqrt(scale) / truncnorm.std(a=a, b=b, loc=0, scale=1) + size = _prod(shape) + samples = truncnorm.rvs(a=a, b=b, loc=0, scale=std, size=size) + samples = np.reshape(samples, shape) + with torch.no_grad(): + weights.copy_(torch.tensor(samples, device=weights.device)) + + +def lecun_normal_init_(weights): + trunc_normal_init_(weights, scale=1.0) + + +def he_normal_init_(weights): + trunc_normal_init_(weights, scale=2.0) + + +def glorot_uniform_init_(weights): + nn.init.xavier_uniform_(weights, gain=1) + + +def final_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def gating_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def normal_init_(weights): + torch.nn.init.kaiming_normal_(weights, nonlinearity="linear") + + +def compute_angles(ca_pos, pts): + batch_size, num_res, num_heads, num_pts, _ = pts.shape + calpha_vecs = (ca_pos[:, :, None, :] - ca_pos[:, None, :, :]) + 1e-10 + calpha_vecs = torch.tile(calpha_vecs[:, :, :, None, None, :], (1, 1, 1, num_heads, num_pts, 1)) + gfa_pts = pts[:, :, None, :, :, :] - torch.tile(ca_pos[:, :, None, None, None, :], (1, 1, num_res, num_heads, num_pts, 1)) + phi_angles = all_atom.calculate_neighbor_angles( + calpha_vecs.reshape(-1, 3), + gfa_pts.reshape(-1, 3) + ).reshape(batch_size, num_res, num_res, num_heads, num_pts) + return phi_angles + +class Linear(nn.Linear): + """ + A Linear layer with built-in nonstandard initializations. Called just + like torch.nn.Linear. + + Implements the initializers in 1.11.4, plus some additional ones found + in the code. + """ + + def __init__( + self, + in_dim: int, + out_dim: int, + bias: bool = True, + init: str = "default", + init_fn: Optional[Callable[[torch.Tensor, torch.Tensor], None]] = None, + ): + """ + Args: + in_dim: + The final dimension of inputs to the layer + out_dim: + The final dimension of layer outputs + bias: + Whether to learn an additive bias. True by default + init: + The initializer to use. Choose from: + + "default": LeCun fan-in truncated normal initialization + "relu": He initialization w/ truncated normal distribution + "glorot": Fan-average Glorot uniform initialization + "gating": Weights=0, Bias=1 + "normal": Normal initialization with std=1/sqrt(fan_in) + "final": Weights=0, Bias=0 + + Overridden by init_fn if the latter is not None. + init_fn: + A custom initializer taking weight and bias as inputs. + Overrides init if not None. + """ + super(Linear, self).__init__(in_dim, out_dim, bias=bias) + + if bias: + with torch.no_grad(): + self.bias.fill_(0) + + if init_fn is not None: + init_fn(self.weight, self.bias) + else: + if init == "default": + lecun_normal_init_(self.weight) + elif init == "relu": + he_normal_init_(self.weight) + elif init == "glorot": + glorot_uniform_init_(self.weight) + elif init == "gating": + gating_init_(self.weight) + if bias: + with torch.no_grad(): + self.bias.fill_(1.0) + elif init == "normal": + normal_init_(self.weight) + elif init == "final": + final_init_(self.weight) + else: + raise ValueError("Invalid init string.") + + +class StructureModuleTransition(nn.Module): + def __init__(self, c): + super(StructureModuleTransition, self).__init__() + + self.c = c + + self.linear_1 = Linear(self.c, self.c, init="relu") + self.linear_2 = Linear(self.c, self.c, init="relu") + self.linear_3 = Linear(self.c, self.c, init="final") + self.relu = nn.ReLU() + self.ln = nn.LayerNorm(self.c) + + def forward(self, s): + s_initial = s + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + s = self.relu(s) + s = self.linear_3(s) + s = s + s_initial + s = self.ln(s) + + return s + +class EdgeTransition(nn.Module): + def __init__( + self, + *, + node_embed_size, + edge_embed_in, + edge_embed_out, + num_layers=2, + node_dilation=2 + ): + super(EdgeTransition, self).__init__() + + bias_embed_size = node_embed_size // node_dilation + self.initial_embed = Linear( + node_embed_size, bias_embed_size, init="relu") + hidden_size = bias_embed_size * 2 + edge_embed_in + trunk_layers = [] + for _ in range(num_layers): + trunk_layers.append(Linear(hidden_size, hidden_size, init="relu")) + trunk_layers.append(nn.ReLU()) + self.trunk = nn.Sequential(*trunk_layers) + self.final_layer = Linear(hidden_size, edge_embed_out, init="final") + self.layer_norm = nn.LayerNorm(edge_embed_out) + + def forward(self, node_embed, edge_embed): + node_embed = self.initial_embed(node_embed) + batch_size, num_res, _ = node_embed.shape + edge_bias = torch.cat([ + torch.tile(node_embed[:, :, None, :], (1, 1, num_res, 1)), + torch.tile(node_embed[:, None, :, :], (1, num_res, 1, 1)), + ], axis=-1) + edge_embed = torch.cat( + [edge_embed, edge_bias], axis=-1).reshape( + batch_size * num_res**2, -1) + edge_embed = self.final_layer(self.trunk(edge_embed) + edge_embed) + edge_embed = self.layer_norm(edge_embed) + edge_embed = edge_embed.reshape( + batch_size, num_res, num_res, -1 + ) + return edge_embed + +class GeometricFrameAttention(nn.Module): + """ + Implements Algorithm 22. + """ + def __init__( + self, + gfa_conf, + geometric_input=True, + geometric_output=True, + inf: float = 1e5, + eps: float = 1e-8, + ): + """ + Args: + c_s: + Single representation channel dimension + c_z: + Pair representation channel dimension + c_hidden: + Hidden channel dimension + no_heads: + Number of attention heads + no_qk_points: + Number of query/key points to generate + no_v_points: + Number of value points to generate + """ + super(GeometricFrameAttention, self).__init__() + self._gfa_conf = gfa_conf + + self.c_s = gfa_conf.c_s + self.c_z = gfa_conf.c_z + self.c_hidden = gfa_conf.c_hidden + self.no_heads = gfa_conf.no_heads + self.no_qk_points = gfa_conf.no_qk_points + self.no_v_points = gfa_conf.no_v_points + self.geometric_input = geometric_input + self.geometric_output = geometric_output + self.inf = inf + self.eps = eps + + # These linear layers differ from their specifications in the + # supplement. There, they lack bias and use Glorot initialization. + # Here as in the official source, they have bias and use the default + # Lecun initialization. + hc = self.c_hidden * self.no_heads + self.linear_q = Linear(self.c_s, hc) + self.linear_kv = Linear(self.c_s, 2 * hc) + + hpq = self.no_heads * self.no_qk_points * 3 + self.linear_q_points = Linear(self.c_s, hpq) + + hpk = self.no_heads * self.no_qk_points * 3 + self.linear_k_points = Linear(self.c_s, hpk) + + if self.geometric_input: + self.linear_v_g = Linear(self.c_s, self.no_v_points * 16) + self.merge_geometric = EquiLinear(2 * self.no_v_points, self.no_heads * self.no_v_points) + else: + self.linear_v_g = Linear(self.c_s, self.no_heads * self.no_v_points * 16) + + self.merge_rel = EquiLinear(self.no_v_points + 1, self.no_v_points) + + self.bilinear_v = PairwiseGeometricBilinear( + self.no_v_points, self.no_v_points + ) + + self.mbc_v = GMBCLayer(self.no_heads * self.no_v_points) + + self.linear_b = Linear(self.c_z, self.no_heads) + self.down_z = Linear(self.c_z, self.c_z // 4) + + self.head_weights = nn.Parameter(torch.zeros((gfa_conf.no_heads))) + gfa_point_weights_init_(self.head_weights) + + self.softmax_weights = nn.Parameter(torch.ones((gfa_conf.no_heads))) + + concat_out_dim = ( + self.c_z // 4 + self.c_hidden + 8 + self.no_v_points * 18 # 16 + 1 + 1 + ) + self.linear_out = Linear(self.no_heads * concat_out_dim, self.c_s, init="final") + + if self.geometric_output: + self.geometric_out = EquiLinear(self.no_heads * self.no_v_points, self.no_v_points) + + self.softmax = nn.Softmax(dim=-1) + self.softplus = nn.Softplus() + + self.point_trafo = point_trafo() + self.ga_norm = ga_norm() + self.ga_versor = ga_versor() + self.ga_inverse_versor = ga_inverse_versor() + self.local_rel_trafo = local_rel_trafo() + + def forward( + self, + s: torch.Tensor, + g: torch.Tensor, + z: Optional[torch.Tensor], + T: torch.Tensor, + mask: torch.Tensor, + _offload_inference: bool = False, + _z_reference_list: Optional[Sequence[torch.Tensor]] = None, + ) -> torch.Tensor: + """ + Args: + s: + [*, N_res, C_s] single representation + z: + [*, N_res, N_res, C_z] pair representation + T: + [*, N_res, 16] versors representing the frames + mask: + [*, N_res] mask + Returns: + [*, N_res, C_s] single representation update + """ + if _offload_inference: + z = _z_reference_list + else: + z = [z] + ####################################### + # Generate scalar and point activations + ####################################### + # [*, N_res, H * C_hidden] + q = self.linear_q(s) + kv = self.linear_kv(s) + + T8 = pu.extract_motor(T) + + # [*, N_res, H, C_hidden] + q = q.view(q.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, 2 * C_hidden] + kv = kv.view(kv.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, C_hidden] + k, v = torch.split(kv, self.c_hidden, dim=-1) + + # [*, N_res, H * P_q * 3] + q_pts = self.linear_q_points(s) + + # This is kind of clunky, but it's how the original does it + # [*, N_res, H * P_q, 3] + q_pts = torch.split(q_pts, q_pts.shape[-1] // 3, dim=-1) + q_pts = torch.stack(q_pts, dim=-1) + + q_pts = self.point_trafo(q_pts, T8.unsqueeze(-2)) + + # [*, N_res, H, P_q, 3] + q_pts = q_pts.view( + q_pts.shape[:-2] + (self.no_heads, self.no_qk_points, 4) + ) + + # [*, N_res, H * P_q * 3] + k_pts = self.linear_k_points(s) + + # [*, N_res, H * P_q, 3] + k_pts = torch.split(k_pts, k_pts.shape[-1] // 3, dim=-1) + k_pts = torch.stack(k_pts, dim=-1) + + k_pts = self.point_trafo(k_pts, T8.unsqueeze(-2)) + + # [*, N_res, H, P_q, 3] + k_pts = k_pts.view(k_pts.shape[:-2] + (self.no_heads, -1, 4)) + + v_g = self.linear_v_g(s) + + if self.geometric_input: + v_g = v_g.view(*v_g.shape[:-1], self.no_v_points, 16) + v_g, _ = self.merge_geometric(torch.cat([v_g, g], dim=-2)) + v_g = v_g.view(*v_g.shape[:-2], self.no_heads, self.no_v_points, 16) + else: + v_g = v_g.view(*v_g.shape[:-1], self.no_heads, self.no_v_points, 16) + + ########################## + # Compute attention scores + ########################## + # [*, N_res, N_res, H] + b = self.linear_b(z[0]) + + if(_offload_inference): + z[0] = z[0].cpu() + + # [*, H, N_res, N_res] + a = torch.matmul( + permute_final_dims(q, (1, 0, 2)), # [*, H, N_res, C_hidden] + permute_final_dims(k, (1, 2, 0)), # [*, H, C_hidden, N_res] + ) + a *= math.sqrt(1.0 / (3 * self.c_hidden)) + a += (math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))) + + # [*, N_res, N_res, H, P_q, 3] + pt_displacement = q_pts.unsqueeze(-4)[..., :3] - k_pts.unsqueeze(-5)[..., :3] + pt_att = pt_displacement ** 2 + + # [*, N_res, N_res, H, P_q] + pt_att = torch.sum(pt_att, dim=-1) + + head_weights = self.softplus(self.head_weights).view( + *((1,) * len(pt_att.shape[:-2]) + (-1, 1)) + ) + head_weights = head_weights * math.sqrt( + 1.0 / (3 * (self.no_qk_points * 9.0 / 2)) + ) + + pt_att = pt_att * head_weights + + # [*, N_res, N_res, H] + pt_att = torch.sum(pt_att, dim=-1) * (-0.5) + # [*, N_res, N_res] + square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2) + # transform mask to int: + square_mask = square_mask.long() + square_mask = self.inf * (square_mask - 1) + + # [*, H, N_res, N_res] + pt_att = permute_final_dims(pt_att, (2, 0, 1)) + + softmax_weights = self.softmax_weights.view(1, -1, 1, 1) + + a = a + pt_att + a = a + square_mask.unsqueeze(-3) + a = self.softmax(a * softmax_weights) + + ################ + # Compute output + ################ + # [*, N_res, H, C_hidden] + o = torch.matmul( + a, v.transpose(-2, -3) + ).transpose(-2, -3) + + # [*, N_res, H * C_hidden] + o = flatten_final_dims(o, 2) + + o_pt = self.ga_versor(v_g, T.unsqueeze(-2).unsqueeze(-3)) + + o_pt = torch.sum( + ( + a[..., None, :, :, None] + * permute_final_dims(o_pt, (1, 3, 0, 2))[..., None, :, :] + ), + dim=-2, + ) + o_pt = permute_final_dims(o_pt, (2, 0, 3, 1)) + + o_pt = self.ga_inverse_versor(o_pt, T.unsqueeze(-2).unsqueeze(-3)) + + v_rel = self.local_rel_trafo(T) + v_rel = torch.matmul(a.transpose(-2, -3), v_rel) + + o_pt, _ = self.merge_rel(torch.cat([o_pt, v_rel.unsqueeze(-2)], dim=-2)) + + o_pt = self.bilinear_v(v_g, o_pt) + + # [*, N_res, H * P_v, 16] + o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 16) + + o_pt = self.mbc_v(o_pt) + + post_mbc_norm, post_mbc_infnorm = self.ga_norm(o_pt) + + if(_offload_inference): + z[0] = z[0].to(o_pt.device) + + # [*, N_res, N_res, C_z // 4] + pair_z = self.down_z(z[0]) + o_pair = torch.matmul(a.transpose(-2, -3), pair_z) + + # [*, N_res, H * C_z // 4] + o_pair = flatten_final_dims(o_pair, 2) + + v_rel = extract_motor(v_rel) + + o_feats = [o, *torch.unbind(o_pt, dim=-1), *torch.unbind(v_rel, dim=-1), post_mbc_norm, post_mbc_infnorm, o_pair] + + # [*, N_res, C_s] + s = self.linear_out( + torch.cat( + o_feats, dim=-1 + ) + ) + + if self.geometric_output: + g, _ = self.geometric_out(o_pt) + else: + g = None + + return s, g, v_rel + +class BackboneUpdate(nn.Module): + + + def __init__(self, c_s, c_g, c_T): + """ + Args: + c_s: + Single representation channel dimension + """ + super(BackboneUpdate, self).__init__() + + self.c_s = c_s + self.c_g = c_g + self.c_T = c_T + + self.linear_hidden = Linear(self.c_s + 16 * self.c_g + 8 * self.c_T, 64) + self.gelu = nn.GELU() + + # Choose initialization such that t=0 and R=1, i.e. the identiy map as update + self.linear_final = Linear(64, 6, init="final") + + def forward(self, s: torch.Tensor, g: torch.Tensor, T_rel:torch.Tensor, T: torch.Tensor, R: torch.Tensor, mask: torch.Tensor = None): + """ + Args: + s: + [*, N_res, C_s] single representation + T: + [*, N_res, c_T, 8] motors representing the frames + g: + [*, N_res, c_g, 16] versors representing the frames + Returns: + [*, N_res, 6] update vector + """ + T_rel = T_rel.reshape(*T_rel.shape[:-2], -1) + g = g.reshape(*g.shape[:-2], -1) + + in_ = torch.cat([s, g, T_rel], dim=-1) + if mask is not None: + in_ = in_ * mask + + update = self.linear_hidden(in_) + update = self.gelu(update) + update = self.linear_final(update) + + # Predict new frames both in the LA and PGA formulation as this avoids unneccessary conversions which would lead to numerical instabilities and nan losses + new_rigid = R.compose_q_update_vec(update, mask) + new_frame = embed_quat_frames(new_rigid.get_rots().get_quats(), new_rigid.get_trans()) + + return new_frame, new_rigid diff --git a/gafl/gafl/models/gafl/flow_model.py b/gafl/gafl/models/gafl/flow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..20ffb87c37bbf84c818864b7279bc3ca4e46a493 --- /dev/null +++ b/gafl/gafl/models/gafl/flow_model.py @@ -0,0 +1,142 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Neural network architecture for the flow model.""" +import torch +import torch.nn as nn + +from gafl.models.node_embedder import NodeEmbedder +from gafl.models.edge_embedder import EdgeEmbedder +from gafl.models import ipa_pytorch +from gafl.data import utils as du +from gafl.models.gafl.pga_utils import embed_frames, EquiLayerNorm +from gafl.models.gafl.cfa import GeometricFrameAttention, Linear, BackboneUpdate + +class FlowModel(nn.Module): + + def __init__(self, model_conf): + super(FlowModel, self).__init__() + + self._model_conf = model_conf + self._gfa_conf = model_conf.gfa + self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE) + self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE) + self.node_embedder = NodeEmbedder(model_conf.node_features) + self.edge_embedder = EdgeEmbedder(model_conf.edge_features) + + # Attention trunk + self.trunk = nn.ModuleDict() + for b in range(self._gfa_conf.num_blocks): + self.trunk[f'gfa_{b}'] = GeometricFrameAttention(self._gfa_conf, geometric_input=bool(b), geometric_output=True) + self.trunk[f'gfa_ln_{b}'] = nn.LayerNorm(self._gfa_conf.c_s) + self.trunk[f'g_ln_{b}'] = EquiLayerNorm() + tfmr_in = self._gfa_conf.c_s + tfmr_layer = nn.TransformerEncoderLayer( + d_model=tfmr_in, + nhead=self._gfa_conf.seq_tfmr_num_heads, + dim_feedforward=tfmr_in, + batch_first=True, + dropout=0.0, + norm_first=False + ) + self.trunk[f'seq_tfmr_{b}'] = nn.TransformerEncoder( + tfmr_layer, self._gfa_conf.seq_tfmr_num_layers, enable_nested_tensor=False) + self.trunk[f'post_tfmr_{b}'] = Linear( + tfmr_in, self._gfa_conf.c_s, init="final") + self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition( + c=self._gfa_conf.c_s) + self.trunk[f'bb_update_{b}'] = BackboneUpdate( + self._gfa_conf.c_s, + self._gfa_conf.no_v_points, + self._gfa_conf.no_heads,) + + if b < self._gfa_conf.num_blocks-1: + # No edge update on the last block. + edge_in = self._model_conf.edge_embed_size + self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition( + node_embed_size=self._gfa_conf.c_s, + edge_embed_in=edge_in, + edge_embed_out=self._model_conf.edge_embed_size, + ) + + def forward(self, input_feats): + # During sampling res_idx is not provided + if 'res_idx' not in input_feats: + res_idx = None + else: + res_idx = input_feats['res_idx'] + + if 'breaks' in input_feats: + breaks = input_feats['breaks'] + else: + breaks = None + + node_mask = input_feats['res_mask'] + edge_mask = node_mask[:, None] * node_mask[:, :, None] + continuous_t = input_feats['t'] + trans_t = input_feats['trans_t'] + rotmats_t = input_feats['rotmats_t'] + + # Initialize node and edge embeddings + init_node_embed = self.node_embedder(continuous_t, node_mask, res_idx=res_idx, breaks=breaks) + if 'trans_sc' not in input_feats: + trans_sc = torch.zeros_like(trans_t) + else: + trans_sc = input_feats['trans_sc'] + init_edge_embed = self.edge_embedder( + init_node_embed, trans_t, trans_sc, edge_mask, res_idx=res_idx, breaks=breaks) + + # Initial rigids + curr_rigids = du.create_rigid(rotmats_t, trans_t,) + curr_rigids = self.rigids_ang_to_nm(curr_rigids) + curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE) + + # Main trunk + init_node_embed = init_node_embed * node_mask[..., None] + node_embed = init_node_embed * node_mask[..., None] + edge_embed = init_edge_embed * edge_mask[..., None] + g = None + for b in range(self._gfa_conf.num_blocks): + gfa_embed, g_gfa, gfa_rel = self.trunk[f'gfa_{b}']( + node_embed, + g, + edge_embed, + curr_frames, + node_mask) + gfa_embed *= node_mask[..., None] + gfa_rel = gfa_rel * node_mask[..., None, None] + node_embed = self.trunk[f'gfa_ln_{b}'](node_embed + gfa_embed) + + if g is not None: + g = self.trunk[f'g_ln_{b}'](g + g_gfa) + else: + g = self.trunk[f'g_ln_{b}'](g_gfa) + g = g * node_mask[..., None, None] + + seq_tfmr_out = self.trunk[f'seq_tfmr_{b}']( + node_embed, src_key_padding_mask=(1 - node_mask).bool()) + node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out) + node_embed = self.trunk[f'node_transition_{b}'](node_embed) + node_embed = node_embed * node_mask[..., None] + curr_frames, curr_rigids = self.trunk[f'bb_update_{b}']( + node_embed, + g, + gfa_rel, + curr_frames, + curr_rigids, + node_mask[..., None],) + + if b < self._gfa_conf.num_blocks-1: + edge_embed = self.trunk[f'edge_transition_{b}']( + node_embed, edge_embed) + edge_embed *= edge_mask[..., None] + + curr_rigids = self.rigids_nm_to_ang(curr_rigids) + pred_trans = curr_rigids.get_trans() + pred_rotmats = curr_rigids.get_rots().get_rot_mats() + + return { + 'pred_trans': pred_trans, + 'pred_rotmats': pred_rotmats, + } \ No newline at end of file diff --git a/gafl/gafl/models/gafl/pga_utils.py b/gafl/gafl/models/gafl/pga_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..daf95497118c0bdff99586a2381483e5ce1b6da6 --- /dev/null +++ b/gafl/gafl/models/gafl/pga_utils.py @@ -0,0 +1,540 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) 2023 Qualcomm Technologies, Inc. +# Licensed under the BSD-3-Clause License. + +import torch +import numpy as np + +from functools import lru_cache + +from gatr.primitives.linear import reverse, _compute_reversal, NUM_PIN_LINEAR_BASIS_ELEMENTS, equi_linear +from gatr.primitives.bilinear import _load_bilinear_basis, geometric_product +from gatr.primitives.dual import _compute_efficient_join +from gatr.utils.einsum import cached_einsum +from gatr.interface.rotation import embed_rotation +from gatr.interface.translation import embed_translation +from gatr.primitives.invariants import compute_inner_product_mask +from gatr.interface.scalar import embed_scalar +from gatr.layers.linear import EquiLinear +from gatr.primitives.invariants import norm + +import math +import torch.nn as nn +from typing import Optional + +from gafl.data.so3_utils import rotmat_to_rotquat + + + +MOTOR_DIMS = [0,5,6,7,8,9,10,15] + +def embed_frames(R, t): + """ + Computes the frame embedding in PGA of a euclidean transformation T = (R, t). + Args: + R: Rotation matrix, shape: [*, N_res, 3, 3] + t: Translation vector, shape: [*, N_res, 3] + Returns: + v: Frame embedding, shape: [*, N_res, 16] + """ + + rotquat = rotmat_to_rotquat(R) + # frameflow lib uses a different quaternion convention than gatr + rotmv = embed_rotation(rotquat[...,[1,2,3,0]]) + transmv = embed_translation(t) #gatr has a strange "-" sign in its implementation + + return geometric_product(transmv, rotmv) + +def embed_quat_frames(Q, t): + """ + Computes the frame embedding in PGA of a euclidean transformation T = (Q, t). + Args: + Q: Quaternion, shape: [*, N_res, 4] + t: Translation vector, shape: [*, N_res, 3] + Returns: + v: Frame embedding, shape: [*, N_res, 16] + """ + + rotmv = embed_rotation(Q[...,[1,2,3,0]]) + transmv = embed_translation(t) + + return geometric_product(transmv, rotmv) + +def reverse_versor(v): + return _compute_reversal(device=v.device, dtype=v.dtype)[MOTOR_DIMS] * v + +def apply_versor(x, v): + + """ + Applies a versor to a multivector. + Args: + x: Multivector to be transformed, shape: [*, 16] + v: Versor, shape: [*, 16] + Returns: + y: Transformed multivector, shape: [*, 16] + """ + + v_inv = reverse(v) + y = geometric_product(v, geometric_product(x, v_inv)) + + return y + + +def apply_inverse_versor(x, v): + + """ + Applies the inverse of a versor to a multivector. + Args: + x: Multivector to be transformed, shape: [*, 16] + v: Versor, shape: [*, 16], Make sure that this is properly normalized! + Returns: + y: Transformed multivector, shape: [*, 16] + """ + + v_inv = reverse(v) + y = geometric_product(v_inv, geometric_product(x, v)) + + return y + +@lru_cache() +def load_point_versor_kernel(device: torch.device, dtype: torch.dtype) -> torch.Tensor: + + gp = _load_bilinear_basis("gp", device=device, dtype=dtype) + c = cached_einsum("ijk, klm -> ijlm", gp[11:15, MOTOR_DIMS, :], gp[:, 11:15, MOTOR_DIMS]) + r = _compute_reversal(device=device, dtype=dtype)[MOTOR_DIMS] + return c * r + +def apply_point_versor(x, v, threshold=1e-3): + + mv = torch.empty(x.shape[:-1] + (4,), device=x.device, dtype=x.dtype) + mv[..., 3] = 1.0 + mv[..., 2] = -x[..., 0] # x-coordinate embedded in x_023 + mv[..., 1] = x[..., 1] # y-coordinate embedded in x_013 + mv[..., 0] = -x[..., 2] # z-coordinate embedded in x_012 + + mv = cached_einsum("i j k l, ... j, ... k, ... l -> ... i", load_point_versor_kernel(device=x.device, dtype=x.dtype), v, mv, v) + return mv + + +def cross_gp(x: torch.Tensor, y: torch.Tensor): + """ + Parameters + ---------- + x : torch.Tensor with shape (..., N_res, 16) + + y : torch.Tensor with shape (..., N_res, 16) + + Returns + ------- + outputs : torch.Tensor with shape (..., N_res, N_res, 16) + """ + + # Select kernel on correct device + gp = _load_bilinear_basis("gp", device=x.device, dtype=x.dtype) + + # Compute geometric product + outputs = cached_einsum("i j k, ... nj, ... mk -> ... nmi", gp, x, y) + + return outputs + +def relative_global_frame_transformation(v): + + v_inv = reverse(v) + v_global = cross_gp(v, v_inv) + + return v_global + +def relative_frame_transformation(v): + """ + Computes invariant and equivariant representations of relative frame transformations between all pairs of frames. + Args: + v: Frame representations for all residues, shape: [*, N_res, 16] + Assume normalized frames v ~v = 1 + + Returns: + v_local: Invariant relative frame transformations, shape: [*, N_res, N_res, 16] + """ + + v_inv = reverse(v) + v_local = cross_gp(v_inv, v) + + return v_local + +# When working with local frames, we do not need to ensure equivariance of the join using a reference multivector +# Also we only want SE(3) equivariance and not E(3) equivariance +def efficient_join( + x: torch.Tensor, y: torch.Tensor +) -> torch.Tensor: + """Computes the join, using the efficient implementation. + + Parameters + ---------- + x : torch.Tensor + Left input multivector. + y : torch.Tensor + Right input multivector. + + Returns + ------- + outputs : torch.Tensor + Equivariant join result. + """ + + kernel = _compute_efficient_join(x.device, x.dtype) + return cached_einsum("i j k , ... j, ... k -> ... i", kernel, x, y) + +def extract_motor(v): + """ + Extracts the motor from a frame embedding in PGA. + Args: + + v: Frame embedding, shape: [*, 16] + Returns: + m: Motor, shape: [*, 8] + """ + return v[..., MOTOR_DIMS] + +def embed_motor(m): + """ + Embeds a motor in a frame embedding in PGA. + Args: + m: Motor, shape: [*, 8] + Returns: + v: Frame embedding, shape: [*, 16] + """ + + v = torch.zeros(m.shape[:-1] + (16,), device=m.device, dtype=m.dtype) + v[..., MOTOR_DIMS] = m + return v + +@lru_cache() +def compute_inf_norm_mask(device=torch.device("cpu")) -> torch.Tensor: + # Invert boolean inner product mask + return ~compute_inner_product_mask(device=device) + +def inf_norm(x: torch.Tensor) -> torch.Tensor: + return torch.linalg.norm(x[..., compute_inf_norm_mask(device=x.device)], dim=-1, keepdim=True) + + +from typing import Tuple +from torch import nn + +def equi_layer_norm( + x: torch.Tensor, channel_dim: int = -2, epsilon: float = 0.01 +) -> torch.Tensor: + + # Compute mean_channels |inputs|^2 + squared_norms = x[..., compute_inner_product_mask(device=x.device)].pow(2).sum(dim=-1, keepdim=True) + squared_norms = torch.mean(squared_norms, dim=channel_dim, keepdim=True) + + # Insure against low-norm tensors (which can arise even when `x.var(dim=-1)` is high b/c some + # entries don't contribute to the inner product / GP norm!) + squared_norms = torch.clamp(squared_norms, epsilon) + + # Rescale inputs + outputs = x / torch.sqrt(squared_norms) + + return outputs + +class EquiLayerNorm(nn.Module): + + def __init__(self, mv_channel_dim=-2, epsilon: float = 0.01): + super().__init__() + self.mv_channel_dim = mv_channel_dim + self.epsilon = epsilon + + def forward( + self, multivectors: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + + outputs_mv = equi_layer_norm( + multivectors, channel_dim=self.mv_channel_dim, epsilon=self.epsilon + ) + + return outputs_mv + +class MVLinear(nn.Module): + + def __init__(self, in_channels: int, out_channels: int, bias: bool = True, splits=1): + super().__init__() + assert out_channels % splits == 0 + + weights = [] + for i in range(splits): + weights.append( + torch.empty((out_channels // splits, in_channels, NUM_PIN_LINEAR_BASIS_ELEMENTS)) + ) + + mv_component_factors, mv_factor = self._compute_init_factors(1.0, 1.0 / np.sqrt(3.0), True) + + # Let us fist consider the multivector outputs. + fan_in = in_channels + bound = mv_factor / np.sqrt(fan_in) + for i in range(splits): + for j, factor in enumerate(mv_component_factors): + nn.init.uniform_(weights[i][..., j], a=-factor * bound, b=factor * bound) + + concatenated_weights = torch.cat(weights, dim=0) + self.weight = nn.Parameter(concatenated_weights) + if bias: + self.bias = nn.Parameter(torch.zeros((out_channels, 1))) + else: + self.bias = None + + def forward( + self, multivectors: torch.Tensor + ): + outputs_mv = equi_linear(multivectors, self.weight) # (..., out_channels, 16) + + if self.bias is not None: + bias = embed_scalar(self.bias) + outputs_mv = outputs_mv + bias + + return outputs_mv, None + + @staticmethod + def _compute_init_factors(gain, additional_factor, use_mv_heuristics): + """Computes prefactors for the initialization. + + See self.reset_parameters(). + """ + mv_factor = gain * additional_factor * np.sqrt(3) + + # Individual factors for each multivector component + if use_mv_heuristics: + mv_component_factors = torch.sqrt( + torch.Tensor([1.0, 4.0, 6.0, 2.0, 0.5, 0.5, 1.5, 1.5, 0.5]) + ) + else: + mv_component_factors = torch.ones(NUM_PIN_LINEAR_BASIS_ELEMENTS) + return mv_component_factors, mv_factor + +class PairwiseGeometricBilinear(nn.Module): + """Geometric bilinear layer between two different sets of multivectors. + + Pin-equivariant map between multivector tensors that constructs new geometric features via + geometric products and the equivariant join (based on a reference vector). + + Parameters + ---------- + in_mv_channels : int + Input multivector channels of `x` + out_mv_channels : int + Output multivector channels + hidden_mv_channels : int or None + Hidden MV channels. If None, uses out_mv_channels. + in_s_channels : int or None + Input scalar channels of `x`. If None, no scalars are expected nor returned. + out_s_channels : int or None + Output scalar channels. If None, no scalars are expected nor returned. + """ + + def __init__( + self, + in_channels: int, + + out_channels: int, + hidden_channels: Optional[int] = None, + ) -> None: + super().__init__() + + # Default options + if hidden_channels is None: + hidden_channels = out_channels + + out_channels_each = hidden_channels // 2 + assert ( + out_channels_each * 2 == hidden_channels + ), "GeometricBilinear needs even channel number" + + self.linear_l = MVLinear(in_channels, 2 * out_channels_each, splits=2) + self.linear_r = MVLinear(in_channels, 2 * out_channels_each, splits=2) + self.out_channels_each = out_channels_each + + # Output linear projection + self.linear_out = EquiLinear( + hidden_channels, out_channels + ) + + def forward( + self, + mv1: torch.Tensor, + mv2: torch.Tensor, + ) -> torch.Tensor: + """Forward pass. + + Parameters + ---------- + mv1 : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors argument 1 + mv2 : torch.Tensor with shape (..., in_mv_channels, 16) + Input multivectors argument 2 + + Returns + ------- + outputs_mv : torch.Tensor with shape (..., self.out_mv_channels, 16) + Output multivectors + """ + + l, _ = self.linear_l(mv1) + r, _ = self.linear_r(mv2) + + gp_out = geometric_product(l[..., :self.out_channels_each, :], r[..., :self.out_channels_each, :]) + join_out = efficient_join(l[..., self.out_channels_each:, :], r[..., self.out_channels_each:, :]) + + # Output linear + out = torch.cat((gp_out, join_out), dim=-2) + out, _ = self.linear_out(out) + + return out + +# Return list of slices, where each element in the list sclices the corresponding grade +def _grade_to_slice(dim): + grade_to_slice = list() + subspaces = torch.as_tensor([math.comb(dim, i) for i in range(dim + 1)]) + for grade in range(dim + 1): + index_start = subspaces[:grade].sum() + index_end = index_start + math.comb(4, grade) + grade_to_slice.append(slice(index_start, index_end)) + return grade_to_slice + +@lru_cache() +def bilinear_product_paths(type='gmt'): + dim = 4 + grade_to_slice = _grade_to_slice(dim) + gp_paths = torch.zeros((dim + 1, dim + 1, dim + 1), dtype=bool) + + if type == 'gmt': + mt = _load_bilinear_basis('gp') + elif type == 'jmt': + mt = _compute_efficient_join() + + for i in range(dim + 1): + for j in range(dim + 1): + for k in range(dim + 1): + s_i = grade_to_slice[i] + s_j = grade_to_slice[j] + s_k = grade_to_slice[k] + + m = mt[s_i, s_j, s_k] + gp_paths[i, j, k] = (m != 0).any() + + return gp_paths + +# Geometric many body contraction layer currently only implemeted for n=3 +class GMBCLayer(nn.Module): + + def __init__(self, num_features): + """ + Args: + num_features: + Number of output features + """ + + super(GMBCLayer, self).__init__() + self.register_buffer("subspaces", torch.as_tensor([math.comb(4, i) for i in range(4 + 1)])) + self.num_features = num_features + + self.register_buffer("gp", bilinear_product_paths('gmt')) + self.register_buffer("jp", bilinear_product_paths('jmt')) + + self.gp_weights = nn.Parameter(torch.empty(num_features, self.gp.sum())) + self.jp_weights = nn.Parameter(torch.empty(num_features, self.jp.sum())) + + self.linear = MVLinear(num_features, 2*num_features, splits=2) + + self.reset_parameters() + + def reset_parameters(self): + torch.nn.init.normal_(self.gp_weights, std=1 / (math.sqrt(4 + 1))) + torch.nn.init.normal_(self.jp_weights, std=1 / (math.sqrt(4 + 1))) + + def _get_weight(self): + gp_weights = torch.zeros( + self.num_features, + *self.gp.size(), + dtype=self.gp_weights.dtype, + device=self.gp_weights.device, + ) + gp_weights[:, self.gp] = self.gp_weights + gp_weights_repeated = ( + gp_weights.repeat_interleave(self.subspaces, dim=-3) + .repeat_interleave(self.subspaces, dim=-2) + .repeat_interleave(self.subspaces, dim=-1) + ) + + jp_weights = torch.zeros( + self.num_features, + *self.jp.size(), + dtype=self.jp_weights.dtype, + device=self.jp_weights.device, + ) + jp_weights[:, self.jp] = self.jp_weights + jp_weights_repeated = ( + jp_weights.repeat_interleave(self.subspaces, dim=-3) + .repeat_interleave(self.subspaces, dim=-2) + .repeat_interleave(self.subspaces, dim=-1) + ) + return _load_bilinear_basis('gp', dtype=self.gp_weights.dtype, device=self.gp_weights.device) * gp_weights_repeated + _compute_efficient_join(dtype=self.gp_weights.dtype, device=self.gp_weights.device) * jp_weights_repeated + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: + [*, C_v] single representation + Returns: + [*, C_s] single representation update + """ + W = self._get_weight() + x, _ = self.linear(x) + return cached_einsum('nijk,...nj,...nk->...ni', W, x[..., :self.num_features, :], x[..., self.num_features:, :]) + x[..., self.num_features:, :] + +class point_trafo(nn.Module): + + def __init__(self): + super(point_trafo, self).__init__() + + def forward(self, x, T): + return apply_point_versor(x, T) + +class ga_norm(nn.Module): + + def __init__(self): + super(ga_norm, self).__init__() + + def forward(self, x): + n = norm(x)[..., 0] + inf_n = inf_norm(x)[..., 0] + return n, inf_n + +class ga_versor(nn.Module): + + def __init__(self): + super(ga_versor, self).__init__() + + def forward(self, x, T): + return apply_versor(x, T) + +class ga_inverse_versor(nn.Module): + + def __init__(self): + super(ga_inverse_versor, self).__init__() + + def forward(self, x, T): + return apply_inverse_versor(x, T) + +class global_rel_trafo(nn.Module): + + def __init__(self): + super(global_rel_trafo, self).__init__() + + def forward(self, T): + return relative_global_frame_transformation(T) + +class local_rel_trafo(nn.Module): + + def __init__(self): + super(local_rel_trafo, self).__init__() + + def forward(self, T): + return relative_frame_transformation(T) \ No newline at end of file diff --git a/gafl/gafl/models/ipa_pytorch.py b/gafl/gafl/models/ipa_pytorch.py new file mode 100644 index 0000000000000000000000000000000000000000..6e58fb5eb8cf1c3ab5c44add6789486861246efe --- /dev/null +++ b/gafl/gafl/models/ipa_pytorch.py @@ -0,0 +1,694 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Modified code of Openfold's IPA.""" + +import numpy as np +import torch +import math +from scipy.stats import truncnorm +import torch.nn as nn +from typing import Optional, Callable, List, Sequence +from openfold.utils.rigid_utils import Rigid + +from gafl.data import all_atom + + +def permute_final_dims(tensor: torch.Tensor, inds: List[int]): + zero_index = -1 * len(inds) + first_inds = list(range(len(tensor.shape[:zero_index]))) + return tensor.permute(first_inds + [zero_index + i for i in inds]) + + +def flatten_final_dims(t: torch.Tensor, no_dims: int): + return t.reshape(t.shape[:-no_dims] + (-1,)) + + +def ipa_point_weights_init_(weights): + with torch.no_grad(): + softplus_inverse_1 = 0.541324854612918 + weights.fill_(softplus_inverse_1) + + +def _prod(nums): + out = 1 + for n in nums: + out = out * n + return out + + +def _calculate_fan(linear_weight_shape, fan="fan_in"): + fan_out, fan_in = linear_weight_shape + + if fan == "fan_in": + f = fan_in + elif fan == "fan_out": + f = fan_out + elif fan == "fan_avg": + f = (fan_in + fan_out) / 2 + else: + raise ValueError("Invalid fan option") + + return f + + +def trunc_normal_init_(weights, scale=1.0, fan="fan_in"): + shape = weights.shape + f = _calculate_fan(shape, fan) + scale = scale / max(1, f) + a = -2 + b = 2 + std = math.sqrt(scale) / truncnorm.std(a=a, b=b, loc=0, scale=1) + size = _prod(shape) + samples = truncnorm.rvs(a=a, b=b, loc=0, scale=std, size=size) + samples = np.reshape(samples, shape) + with torch.no_grad(): + weights.copy_(torch.tensor(samples, device=weights.device)) + + +def lecun_normal_init_(weights): + trunc_normal_init_(weights, scale=1.0) + + +def he_normal_init_(weights): + trunc_normal_init_(weights, scale=2.0) + + +def glorot_uniform_init_(weights): + nn.init.xavier_uniform_(weights, gain=1) + + +def final_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def gating_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def normal_init_(weights): + torch.nn.init.kaiming_normal_(weights, nonlinearity="linear") + + +def compute_angles(ca_pos, pts): + batch_size, num_res, num_heads, num_pts, _ = pts.shape + calpha_vecs = (ca_pos[:, :, None, :] - ca_pos[:, None, :, :]) + 1e-10 + calpha_vecs = torch.tile(calpha_vecs[:, :, :, None, None, :], (1, 1, 1, num_heads, num_pts, 1)) + ipa_pts = pts[:, :, None, :, :, :] - torch.tile(ca_pos[:, :, None, None, None, :], + (1, 1, num_res, num_heads, num_pts, 1)) + phi_angles = all_atom.calculate_neighbor_angles( + calpha_vecs.reshape(-1, 3), + ipa_pts.reshape(-1, 3) + ).reshape(batch_size, num_res, num_res, num_heads, num_pts) + return phi_angles + + +class Linear(nn.Linear): + """ + A Linear layer with built-in nonstandard initializations. Called just + like torch.nn.Linear. + + Implements the initializers in 1.11.4, plus some additional ones found + in the code. + """ + + def __init__( + self, + in_dim: int, + out_dim: int, + bias: bool = True, + init: str = "default", + init_fn: Optional[Callable[[torch.Tensor, torch.Tensor], None]] = None, + ): + """ + Args: + in_dim: + The final dimension of inputs to the layer + out_dim: + The final dimension of layer outputs + bias: + Whether to learn an additive bias. True by default + init: + The initializer to use. Choose from: + + "default": LeCun fan-in truncated normal initialization + "relu": He initialization w/ truncated normal distribution + "glorot": Fan-average Glorot uniform initialization + "gating": Weights=0, Bias=1 + "normal": Normal initialization with std=1/sqrt(fan_in) + "final": Weights=0, Bias=0 + + Overridden by init_fn if the latter is not None. + init_fn: + A custom initializer taking weight and bias as inputs. + Overrides init if not None. + """ + super(Linear, self).__init__(in_dim, out_dim, bias=bias) + + if bias: + with torch.no_grad(): + self.bias.fill_(0) + + if init_fn is not None: + init_fn(self.weight, self.bias) + else: + if init == "default": + lecun_normal_init_(self.weight) + elif init == "relu": + he_normal_init_(self.weight) + elif init == "glorot": + glorot_uniform_init_(self.weight) + elif init == "gating": + gating_init_(self.weight) + if bias: + with torch.no_grad(): + self.bias.fill_(1.0) + elif init == "normal": + normal_init_(self.weight) + elif init == "final": + final_init_(self.weight) + else: + raise ValueError("Invalid init string.") + + +class StructureModuleTransition(nn.Module): + def __init__(self, c): + super(StructureModuleTransition, self).__init__() + + self.c = c + + self.linear_1 = Linear(self.c, self.c, init="relu") + self.linear_2 = Linear(self.c, self.c, init="relu") + self.linear_3 = Linear(self.c, self.c, init="final") + self.relu = nn.ReLU() + self.ln = nn.LayerNorm(self.c) + + def forward(self, s): + s_initial = s + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + s = self.relu(s) + s = self.linear_3(s) + s = s + s_initial + s = self.ln(s) + + return s + + +class EdgeTransition(nn.Module): + def __init__( + self, + *, + node_embed_size, + edge_embed_in, + edge_embed_out, + num_layers=2, + node_dilation=2 + ): + super(EdgeTransition, self).__init__() + + bias_embed_size = node_embed_size // node_dilation + self.initial_embed = Linear( + node_embed_size, bias_embed_size, init="relu") + hidden_size = bias_embed_size * 2 + edge_embed_in + trunk_layers = [] + for _ in range(num_layers): + trunk_layers.append(Linear(hidden_size, hidden_size, init="relu")) + trunk_layers.append(nn.ReLU()) + self.trunk = nn.Sequential(*trunk_layers) + self.final_layer = Linear(hidden_size, edge_embed_out, init="final") + self.layer_norm = nn.LayerNorm(edge_embed_out) + + def forward(self, node_embed, edge_embed): + node_embed = self.initial_embed(node_embed) + batch_size, num_res, _ = node_embed.shape + edge_embed = torch.cat( + [ + edge_embed, + node_embed[:, :, None, :].expand(-1, -1, num_res, -1), + node_embed[:, None, :, :].expand(-1, num_res, -1, -1), + ], + dim=-1, + ).reshape(batch_size * num_res ** 2, -1) + edge_embed = self.final_layer(self.trunk(edge_embed) + edge_embed) + edge_embed = self.layer_norm(edge_embed) + edge_embed = edge_embed.reshape( + batch_size, num_res, num_res, -1 + ) + return edge_embed + + +class InvariantPointAttention(nn.Module): + """ + Implements Algorithm 22. + """ + + def __init__( + self, + ipa_conf, + inf: float = 1e5, + eps: float = 1e-8, + ): + """ + Args: + c_s: + Single representation channel dimension + c_z: + Pair representation channel dimension + c_hidden: + Hidden channel dimension + no_heads: + Number of attention heads + no_qk_points: + Number of query/key points to generate + no_v_points: + Number of value points to generate + """ + super(InvariantPointAttention, self).__init__() + self._ipa_conf = ipa_conf + + self.c_s = ipa_conf.c_s + self.c_z = ipa_conf.c_z + self.c_hidden = ipa_conf.c_hidden + self.no_heads = ipa_conf.no_heads + self.no_qk_points = ipa_conf.no_qk_points + self.no_v_points = ipa_conf.no_v_points + self.inf = inf + self.eps = eps + + # These linear layers differ from their specifications in the + # supplement. There, they lack bias and use Glorot initialization. + # Here as in the official source, they have bias and use the default + # Lecun initialization. + hc = self.c_hidden * self.no_heads + self.linear_q = Linear(self.c_s, hc) + self.linear_kv = Linear(self.c_s, 2 * hc) + + hpq = self.no_heads * self.no_qk_points * 3 + self.linear_q_points = Linear(self.c_s, hpq) + + hpkv = self.no_heads * (self.no_qk_points + self.no_v_points) * 3 + self.linear_kv_points = Linear(self.c_s, hpkv) + + self.linear_b = Linear(self.c_z, self.no_heads) + self.down_z = Linear(self.c_z, self.c_z // 4) + + self.head_weights = nn.Parameter(torch.zeros((ipa_conf.no_heads))) + ipa_point_weights_init_(self.head_weights) + + concat_out_dim = ( + self.c_z // 4 + self.c_hidden + self.no_v_points * 4 + ) + self.linear_out = Linear(self.no_heads * concat_out_dim, self.c_s, init="final") + + self.softmax = nn.Softmax(dim=-1) + self.softplus = nn.Softplus() + + def forward( + self, + s: torch.Tensor, + z: Optional[torch.Tensor], + r: Rigid, + mask: torch.Tensor, + _offload_inference: bool = False, + _z_reference_list: Optional[Sequence[torch.Tensor]] = None, + ) -> torch.Tensor: + """ + Args: + s: + [*, N_res, C_s] single representation + z: + [*, N_res, N_res, C_z] pair representation + r: + [*, N_res] transformation object + mask: + [*, N_res] mask + Returns: + [*, N_res, C_s] single representation update + """ + if _offload_inference: + z = _z_reference_list + else: + z = [z] + + ####################################### + # Generate scalar and point activations + ####################################### + # [*, N_res, H * C_hidden] + q = self.linear_q(s) + kv = self.linear_kv(s) + + # [*, N_res, H, C_hidden] + q = q.view(q.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, 2 * C_hidden] + kv = kv.view(kv.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, C_hidden] + k, v = torch.split(kv, self.c_hidden, dim=-1) + + # [*, N_res, H * P_q * 3] + q_pts = self.linear_q_points(s) + + # This is kind of clunky, but it's how the original does it + # [*, N_res, H * P_q, 3] + q_pts = torch.split(q_pts, q_pts.shape[-1] // 3, dim=-1) + q_pts = torch.stack(q_pts, dim=-1) + q_pts = r[..., None].apply(q_pts) + + # [*, N_res, H, P_q, 3] + q_pts = q_pts.view( + q_pts.shape[:-2] + (self.no_heads, self.no_qk_points, 3) + ) + + # [*, N_res, H * (P_q + P_v) * 3] + kv_pts = self.linear_kv_points(s) + + # [*, N_res, H * (P_q + P_v), 3] + kv_pts = torch.split(kv_pts, kv_pts.shape[-1] // 3, dim=-1) + kv_pts = torch.stack(kv_pts, dim=-1) + kv_pts = r[..., None].apply(kv_pts) + + # [*, N_res, H, (P_q + P_v), 3] + kv_pts = kv_pts.view(kv_pts.shape[:-2] + (self.no_heads, -1, 3)) + + # [*, N_res, H, P_q/P_v, 3] + k_pts, v_pts = torch.split( + kv_pts, [self.no_qk_points, self.no_v_points], dim=-2 + ) + + ########################## + # Compute attention scores + ########################## + # [*, N_res, N_res, H] + b = self.linear_b(z[0]) + + if (_offload_inference): + z[0] = z[0].cpu() + + # [*, H, N_res, N_res] + a = torch.matmul( + permute_final_dims(q, (1, 0, 2)), # [*, H, N_res, C_hidden] + permute_final_dims(k, (1, 2, 0)), # [*, H, C_hidden, N_res] + ) + a *= math.sqrt(1.0 / (3 * self.c_hidden)) + a += (math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))) + + # [*, N_res, N_res, H, P_q, 3] + pt_displacement = q_pts.unsqueeze(-4) - k_pts.unsqueeze(-5) + pt_att = pt_displacement ** 2 + + # [*, N_res, N_res, H, P_q] + pt_att = sum(torch.unbind(pt_att, dim=-1)) + head_weights = self.softplus(self.head_weights).view( + *((1,) * len(pt_att.shape[:-2]) + (-1, 1)) + ) + head_weights = head_weights * math.sqrt( + 1.0 / (3 * (self.no_qk_points * 9.0 / 2)) + ) + pt_att = pt_att * head_weights + + # [*, N_res, N_res, H] + pt_att = torch.sum(pt_att, dim=-1) * (-0.5) + # [*, N_res, N_res] + square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2) + square_mask = self.inf * (square_mask - 1) + + # [*, H, N_res, N_res] + pt_att = permute_final_dims(pt_att, (2, 0, 1)) + + a = a + pt_att + a = a + square_mask.unsqueeze(-3) + a = self.softmax(a) + + ################ + # Compute output + ################ + # [*, N_res, H, C_hidden] + o = torch.matmul( + a, v.transpose(-2, -3) + ).transpose(-2, -3) + + # [*, N_res, H * C_hidden] + o = flatten_final_dims(o, 2) + + # [*, H, 3, N_res, P_v] + o_pt = torch.sum( + ( + a[..., None, :, :, None] + * permute_final_dims(v_pts, (1, 3, 0, 2))[..., None, :, :] + ), + dim=-2, + ) + + # [*, N_res, H, P_v, 3] + o_pt = permute_final_dims(o_pt, (2, 0, 3, 1)) + o_pt = r[..., None, None].invert_apply(o_pt) + + # [*, N_res, H * P_v] + o_pt_dists = torch.sqrt(torch.sum(o_pt ** 2, dim=-1) + self.eps) + o_pt_norm_feats = flatten_final_dims( + o_pt_dists, 2) + + # [*, N_res, H * P_v, 3] + o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 3) + + if (_offload_inference): + z[0] = z[0].to(o_pt.device) + + # [*, N_res, N_res, C_z // 4] + pair_z = self.down_z(z[0]) + o_pair = torch.matmul(a.transpose(-2, -3), pair_z) + + # [*, N_res, H * C_z // 4] + o_pair = flatten_final_dims(o_pair, 2) + + o_feats = [o, *torch.unbind(o_pt, dim=-1), o_pt_norm_feats, o_pair] + + # [*, N_res, C_s] + s = self.linear_out( + torch.cat( + o_feats, dim=-1 + ) + ) + + return s + + +class TorsionAngles(nn.Module): + def __init__(self, c, num_torsions, eps=1e-8): + super(TorsionAngles, self).__init__() + + self.c = c + self.eps = eps + self.num_torsions = num_torsions + + self.linear_1 = Linear(self.c, self.c, init="relu") + self.linear_2 = Linear(self.c, self.c, init="relu") + # TODO: Remove after published checkpoint is updated without these weights. + self.linear_3 = Linear(self.c, self.c, init="final") + self.linear_final = Linear( + self.c, self.num_torsions * 2, init="final") + + self.relu = nn.ReLU() + + def forward(self, s): + s_initial = s + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + + s = s + s_initial + unnormalized_s = self.linear_final(s) + norm_denom = torch.sqrt( + torch.clamp( + torch.sum(unnormalized_s ** 2, dim=-1, keepdim=True), + min=self.eps, + ) + ) + normalized_s = unnormalized_s / norm_denom + + return unnormalized_s, normalized_s + + +class RotationVFLayer(nn.Module): + def __init__(self, dim): + super(RotationVFLayer, self).__init__() + + self.linear_1 = Linear(dim, dim, init="relu") + self.linear_2 = Linear(dim, dim, init="relu") + self.linear_3 = Linear(dim, dim) + self.final_linear = Linear(dim, 6, init="final") + self.relu = nn.ReLU() + + def forward(self, s): + s_initial = s + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + s = self.relu(s) + s = self.linear_3(s) + s = s + s_initial + return self.final_linear(s) + + +class BackboneUpdate(nn.Module): + """ + Implements part of Algorithm 23. + """ + + def __init__(self, c_s, use_rot_updates): + """ + Args: + c_s: + Single representation channel dimension + """ + super(BackboneUpdate, self).__init__() + + self.c_s = c_s + self._use_rot_updates = use_rot_updates + update_dim = 6 if use_rot_updates else 3 + self.linear = Linear(self.c_s, update_dim, init="final") + + def forward(self, s: torch.Tensor): + """ + Args: + [*, N_res, C_s] single representation + Returns: + [*, N_res, 6] update vector + """ + # [*, 6] + update = self.linear(s) + + return update + + +class IpaScore(nn.Module): + + def __init__(self, model_conf, diffuser): + super(IpaScore, self).__init__() + self._model_conf = model_conf + ipa_conf = model_conf.ipa + self._ipa_conf = ipa_conf + self.diffuser = diffuser + + self.scale_pos = lambda x: x * ipa_conf.coordinate_scaling + self.scale_rigids = lambda x: x.apply_trans_fn(self.scale_pos) + + self.unscale_pos = lambda x: x / ipa_conf.coordinate_scaling + self.unscale_rigids = lambda x: x.apply_trans_fn(self.unscale_pos) + self.trunk = nn.ModuleDict() + + for b in range(ipa_conf.num_blocks): + self.trunk[f'ipa_{b}'] = InvariantPointAttention(ipa_conf) + self.trunk[f'ipa_ln_{b}'] = nn.LayerNorm(ipa_conf.c_s) + self.trunk[f'skip_embed_{b}'] = Linear( + self._model_conf.node_embed_size, + self._ipa_conf.c_skip, + init="final" + ) + tfmr_in = ipa_conf.c_s + self._ipa_conf.c_skip + tfmr_layer = torch.nn.TransformerEncoderLayer( + d_model=tfmr_in, + nhead=ipa_conf.seq_tfmr_num_heads, + dim_feedforward=tfmr_in, + batch_first=True, + dropout=0.0, + norm_first=False + ) + self.trunk[f'seq_tfmr_{b}'] = torch.nn.TransformerEncoder( + tfmr_layer, ipa_conf.seq_tfmr_num_layers) + self.trunk[f'post_tfmr_{b}'] = Linear( + tfmr_in, ipa_conf.c_s, init="final") + self.trunk[f'node_transition_{b}'] = StructureModuleTransition( + c=ipa_conf.c_s) + self.trunk[f'bb_update_{b}'] = BackboneUpdate(ipa_conf.c_s) + + if b < ipa_conf.num_blocks - 1: + # No edge update on the last block. + edge_in = self._model_conf.edge_embed_size + self.trunk[f'edge_transition_{b}'] = EdgeTransition( + node_embed_size=ipa_conf.c_s, + edge_embed_in=edge_in, + edge_embed_out=self._model_conf.edge_embed_size, + ) + + self.torsion_pred = TorsionAngles(ipa_conf.c_s, 1) + + def forward(self, init_node_embed, edge_embed, input_feats): + node_mask = input_feats['res_mask'].type(torch.float32) + diffuse_mask = (1 - input_feats['fixed_mask'].type(torch.float32)) * node_mask + edge_mask = node_mask[..., None] * node_mask[..., None, :] + init_frames = input_feats['rigids_t'].type(torch.float32) + + curr_rigids = Rigid.from_tensor_7(torch.clone(init_frames)) + init_rigids = Rigid.from_tensor_7(init_frames) + init_rots = init_rigids.get_rots() + + # Main trunk + curr_rigids = self.scale_rigids(curr_rigids) + init_node_embed = init_node_embed * node_mask[..., None] + node_embed = init_node_embed * node_mask[..., None] + for b in range(self._ipa_conf.num_blocks): + ipa_embed = self.trunk[f'ipa_{b}']( + node_embed, + edge_embed, + curr_rigids, + node_mask) + ipa_embed *= node_mask[..., None] + node_embed = self.trunk[f'ipa_ln_{b}'](node_embed + ipa_embed) + seq_tfmr_in = torch.cat([ + node_embed, self.trunk[f'skip_embed_{b}'](init_node_embed) + ], dim=-1) + seq_tfmr_out = self.trunk[f'seq_tfmr_{b}']( + seq_tfmr_in, src_key_padding_mask=1 - node_mask) + node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out) + node_embed = self.trunk[f'node_transition_{b}'](node_embed) + node_embed = node_embed * node_mask[..., None] + rigid_update = self.trunk[f'bb_update_{b}']( + node_embed * diffuse_mask[..., None]) + curr_rigids = curr_rigids.compose_q_update_vec( + rigid_update, diffuse_mask[..., None]) + + if b < self._ipa_conf.num_blocks - 1: + edge_embed = self.trunk[f'edge_transition_{b}']( + node_embed, edge_embed) + edge_embed *= edge_mask[..., None] + rot_score = self.diffuser.calc_rot_score( + init_rigids.get_rots(), + curr_rigids.get_rots(), + input_feats['t'] + ) + rot_score = rot_score * node_mask[..., None] + + curr_rigids = self.unscale_rigids(curr_rigids) + trans_score = self.diffuser.calc_trans_score( + init_rigids.get_trans(), + curr_rigids.get_trans(), + input_feats['t'][:, None, None], + use_torch=True, + ) + trans_score = trans_score * node_mask[..., None] + _, psi_pred = self.torsion_pred(node_embed) + model_out = { + 'psi': psi_pred, + 'rot_score': rot_score, + 'trans_score': trans_score, + 'final_rigids': curr_rigids, + } + return model_out diff --git a/gafl/gafl/models/node_embedder.py b/gafl/gafl/models/node_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..9918688704522a287ba42637d435c967b3737859 --- /dev/null +++ b/gafl/gafl/models/node_embedder.py @@ -0,0 +1,94 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Neural network for embedding node features.""" +import torch +from torch import nn + +from gafl.models.utils import get_index_embedding, get_time_embedding, get_length_embedding + + +class NodeEmbedder(nn.Module): + + def __init__(self, module_cfg): + super(NodeEmbedder, self).__init__() + self._cfg = module_cfg + + if "permutation_equivariance" in self._cfg: + self.permutation_equivariance = self._cfg.permutation_equivariance + else: + self.permutation_equivariance = False + + if "total_length_emb_dim" in self._cfg: + self.total_length_emb_dim = self._cfg.total_length_emb_dim + else: + self.total_length_emb_dim = 0 + + if "embed_breaks" in self._cfg: + self.embed_breaks = self._cfg.embed_breaks + else: + self.embed_breaks = False + + if self.embed_breaks: + self.c_breaks = 2 + else: + self.c_breaks = 0 + + self.c_s = self._cfg.c_s + self.c_pos_emb = self._cfg.c_pos_emb + self.c_timestep_emb = self._cfg.c_timestep_emb + self.linear = nn.Linear( + self._cfg.c_pos_emb + self._cfg.c_timestep_emb, self.c_s) + + def embed_t(self, timesteps, mask): + timestep_emb = get_time_embedding( + timesteps[:, 0], + self.c_timestep_emb, + max_positions=2056 + )[:, None, :].repeat(1, mask.shape[1], 1) + return timestep_emb * mask.unsqueeze(-1) + + def forward(self, timesteps, mask, res_idx=None, breaks=None): + # s: [b] + + b, num_res, device = mask.shape[0], mask.shape[1], mask.device + + if res_idx is None: + pos = torch.arange(num_res, dtype=torch.float32).to(device).unsqueeze(0) + else: + pos = res_idx.float() + + if self.permutation_equivariance: + # NOTE: remove positional encoding, except for first and last residue + pos[:, 1:-1] = torch.ones_like(pos[:, 1:-1]) + # set the first residue to 0 and the last to 2, then multiply by half of max len + pos[:, 0] = 0 + pos[:, -1] = 2 + pos = pos * 1028 + + pos_emb = get_index_embedding( + pos, self.c_pos_emb-self.total_length_emb_dim-self.c_breaks, max_len=2056 + ) + + # [b, n_res, c_pos_emb] + if res_idx is None: + pos_emb = pos_emb.repeat([b, 1, 1]) + + if self.embed_breaks: + if breaks is None: + breaks = torch.zeros([b, num_res], device=device, dtype=torch.float32) + pos_emb = torch.cat([pos_emb, breaks.unsqueeze(-1), (1 - breaks).unsqueeze(-1)], dim=-1) + + if self.total_length_emb_dim > 0: + length_embedding = get_length_embedding(pos, embed_size=self.total_length_emb_dim, max_len=2056) + length_embedding = length_embedding.repeat([b, 1, 1]) + pos_emb = torch.cat([pos_emb, length_embedding], dim=-1) + + pos_emb = pos_emb * mask.unsqueeze(-1) + + # [b, n_res, c_timestep_emb] + input_feats = [pos_emb] + # timesteps are between 0 and 1. Convert to integers. + input_feats.append(self.embed_t(timesteps, mask)) + return self.linear(torch.cat(input_feats, dim=-1)) \ No newline at end of file diff --git a/gafl/gafl/models/utils.py b/gafl/gafl/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ddec7c324b0f7fa1e8b64e94dcc7bb684b9e29 --- /dev/null +++ b/gafl/gafl/models/utils.py @@ -0,0 +1,136 @@ +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import math +import torch +from torch.nn import functional as F +import numpy as np +import importlib + +from gafl.data import utils as du + + +def load_module(object): + module, object = object.rsplit(".", 1) + + # backwards compatibility (there used to be no gafl package): + if not module.startswith("gafl."): + module = "gafl." + module + + module = importlib.import_module(module) + fn = getattr(module, object) + return fn + +def calc_distogram(pos, min_bin, max_bin, num_bins): + dists_2d = torch.linalg.norm( + pos[:, :, None, :] - pos[:, None, :, :], axis=-1)[..., None] + lower = torch.linspace( + min_bin, + max_bin, + num_bins, + device=pos.device) + upper = torch.cat([lower[1:], lower.new_tensor([1e8])], dim=-1) + dgram = ((dists_2d > lower) * (dists_2d < upper)).type(pos.dtype) + return dgram + +def log_bin_values(values, x_min, x_max, n_bins, device='cpu'): + assert x_min > 1, "x_min must be greater than 1" + assert x_max > x_min, "x_max must be greater than x_min" + # assert torch.all(values >= x_min), "All values must be greater than or equal to x_min" + # assert torch.all(values <= x_max), "All values must be less than or equal to x_max" + + # clip values to be within the range + values_ = torch.clamp(values, x_min, x_max) + + # Generate logarithmic bins + bins = torch.logspace(torch.log10(torch.tensor(x_min-1, device=device)), + torch.log10(torch.tensor(x_max, device=device)), + n_bins + 1, device=device) + + # Bucketize values into bins + bin_indices = torch.bucketize(values_, bins, right=True) - 1 + + return bin_indices + +def get_length_embedding(indices, embed_size, max_len=2056): + """ + Creates an embedding of total lengths using log-space binning. + + Args: + indices: shape [..., N_res] + embed_size: dimension of the embeddings to create + max_len: maximum length. + + Returns: + embedding of shape [..., N_res, embed_size] + """ + + # additional length embedding using one-hot encoding of binned lengths (logarithmic bins) + ############################## + num_res = indices.shape[-1] + num_res = torch.tensor((num_res), device=indices.device).float() + + # log binning + binned_values = log_bin_values(values=num_res, x_min=60, x_max=max_len, n_bins=embed_size, device=indices.device) + binned_values = F.one_hot(binned_values, num_classes=embed_size).float() + + # Shape adjustment to match input shape + expanded_shape = list(indices.shape) + [1] + binned_values = binned_values.repeat(*expanded_shape) + return binned_values + +def get_index_embedding(indices, embed_size, max_len=2056): + """Creates sine / cosine positional embeddings from a prespecified indices. + + Args: + indices: offsets of size [..., N_edges] of type integer + max_len: maximum length. + embed_size: dimension of the embeddings to create + + Returns: + positional embedding of shape [N, embed_size] + """ + K = torch.arange(embed_size//2, device=indices.device) + pos_embedding_sin = torch.sin( + indices[..., None] * math.pi / (max_len**(2*K[None]/embed_size))).to(indices.device) + pos_embedding_cos = torch.cos( + indices[..., None] * math.pi / (max_len**(2*K[None]/embed_size))).to(indices.device) + pos_embedding = torch.cat([ + pos_embedding_sin, pos_embedding_cos], axis=-1) + return pos_embedding + +def get_time_embedding(timesteps, embedding_dim, max_positions=2000): + # Code from https://github.com/hojonathanho/diffusion/blob/master/diffusion_tf/nn.py + assert len(timesteps.shape) == 1 + timesteps = timesteps * max_positions + half_dim = embedding_dim // 2 + emb = math.log(max_positions) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, dtype=torch.float32, device=timesteps.device) * -emb) + emb = timesteps.float()[:, None] * emb[None, :] + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) + if embedding_dim % 2 == 1: # zero pad + emb = F.pad(emb, (0, 1), mode='constant') + assert emb.shape == (timesteps.shape[0], embedding_dim) + return emb + +def t_stratified_loss(batch_t, batch_loss, num_bins=4, t_interval=[0.0, 1.0], loss_name=None): + """Stratify loss by binning t.""" + batch_t = du.to_numpy(batch_t) + batch_loss = du.to_numpy(batch_loss) + flat_losses = batch_loss.flatten() + flat_t = batch_t.flatten() + bin_edges = np.linspace(t_interval[0], t_interval[1] + 1e-3, num_bins+1) + bin_idx = np.sum(bin_edges[:, None] <= flat_t[None, :], axis=0) - 1 + t_binned_loss = np.bincount(bin_idx, weights=flat_losses) + t_binned_n = np.bincount(bin_idx) + stratified_losses = {} + if loss_name is None: + loss_name = 'loss' + for t_bin in np.unique(bin_idx).tolist(): + bin_start = bin_edges[t_bin] + bin_end = bin_edges[t_bin+1] + t_range = f'{loss_name} t=[{bin_start:.2f},{bin_end:.2f})' + range_loss = t_binned_loss[t_bin] / t_binned_n[t_bin] + stratified_losses[t_range] = range_loss + return stratified_losses \ No newline at end of file diff --git a/gafl/install_gatr.sh b/gafl/install_gatr.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8a0f637ab924829ea02f8670683eee5b699808a --- /dev/null +++ b/gafl/install_gatr.sh @@ -0,0 +1,16 @@ +url=https://github.com/Qualcomm-AI-research/geometric-algebra-transformer.git +project_dir=geometric-algebra-transformer +# commit ID of version 1.2.0 +commit_id=87fa7d0c5cec5d874b13814816c628843e348866 +mkdir build +cd build +echo "Cloning gatr repository" +git clone $url +cd $project_dir +git reset --hard $commit_id +echo "Applying patch 1/2: remove dependency on xformers" +git apply ../../patches/gatr_xformers.patch +echo "Applying patch 2/2: improvements of runtime performance" +git apply ../../patches/gatr_performance.patch +echo "Installing gatr package" +pip install --no-deps . diff --git a/gafl/openfold/__pycache__/config.cpython-310.pyc b/gafl/openfold/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58472cd1dd49e5208a2759b3b1694ddec0dfbd6a Binary files /dev/null and b/gafl/openfold/__pycache__/config.cpython-310.pyc differ diff --git a/gafl/openfold/__pycache__/config.cpython-311.pyc b/gafl/openfold/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4d76dfaa8ef0bf0460fb2e339ed211257442983 Binary files /dev/null and b/gafl/openfold/__pycache__/config.cpython-311.pyc differ diff --git a/gafl/openfold/config.py b/gafl/openfold/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b73acb91d367c07f3c99cf7400883041baf67a7a --- /dev/null +++ b/gafl/openfold/config.py @@ -0,0 +1,4 @@ +NUM_RES = "num residues placeholder" +NUM_MSA_SEQ = "msa placeholder" +NUM_EXTRA_SEQ = "extra msa placeholder" +NUM_TEMPLATES = "num templates placeholder" diff --git a/gafl/openfold/data/__init__.py b/gafl/openfold/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/openfold/data/__pycache__/__init__.cpython-310.pyc b/gafl/openfold/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243430b3354921fc05b32d70724e5b792841c52d Binary files /dev/null and b/gafl/openfold/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/gafl/openfold/data/__pycache__/__init__.cpython-311.pyc b/gafl/openfold/data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7329ba7edafeeea194cede07e5ba23eef99b60aa Binary files /dev/null and b/gafl/openfold/data/__pycache__/__init__.cpython-311.pyc differ diff --git a/gafl/openfold/data/__pycache__/data_transforms.cpython-310.pyc b/gafl/openfold/data/__pycache__/data_transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f136d549ba489ffca7a848b7023bd4af06f7248d Binary files /dev/null and b/gafl/openfold/data/__pycache__/data_transforms.cpython-310.pyc differ diff --git a/gafl/openfold/data/__pycache__/data_transforms.cpython-311.pyc b/gafl/openfold/data/__pycache__/data_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd0c03da6e22e019b074beb17e2e566cb9d79f9d Binary files /dev/null and b/gafl/openfold/data/__pycache__/data_transforms.cpython-311.pyc differ diff --git a/gafl/openfold/data/data_modules.py b/gafl/openfold/data/data_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..fec88f02607b8366552658583213bdbdb49db7c4 --- /dev/null +++ b/gafl/openfold/data/data_modules.py @@ -0,0 +1,693 @@ +import copy +from functools import partial +import json +import logging +import os +import pickle +from typing import Optional, Sequence, List, Any + +import ml_collections as mlc +import numpy as np +import pytorch_lightning as pl +import torch +from torch.utils.data import RandomSampler + +from openfold.data import ( + data_pipeline, + feature_pipeline, + mmcif_parsing, + templates, +) +from openfold.utils.tensor_utils import tensor_tree_map, dict_multimap + + +class OpenFoldSingleDataset(torch.utils.data.Dataset): + def __init__(self, + data_dir: str, + alignment_dir: str, + template_mmcif_dir: str, + max_template_date: str, + config: mlc.ConfigDict, + kalign_binary_path: str = '/usr/bin/kalign', + max_template_hits: int = 4, + obsolete_pdbs_file_path: Optional[str] = None, + template_release_dates_cache_path: Optional[str] = None, + shuffle_top_k_prefiltered: Optional[int] = None, + treat_pdb_as_distillation: bool = True, + mapping_path: Optional[str] = None, + mode: str = "train", + _output_raw: bool = False, + _alignment_index: Optional[Any] = None + ): + """ + Args: + data_dir: + A path to a directory containing mmCIF files (in train + mode) or FASTA files (in inference mode). + alignment_dir: + A path to a directory containing only data in the format + output by an AlignmentRunner + (defined in openfold.features.alignment_runner). + I.e. a directory of directories named {PDB_ID}_{CHAIN_ID} + or simply {PDB_ID}, each containing .a3m, .sto, and .hhr + files. + template_mmcif_dir: + Path to a directory containing template mmCIF files. + config: + A dataset config object. See openfold.config + kalign_binary_path: + Path to kalign binary. + max_template_hits: + An upper bound on how many templates are considered. During + training, the templates ultimately used are subsampled + from this total quantity. + template_release_dates_cache_path: + Path to the output of scripts/generate_mmcif_cache. + obsolete_pdbs_file_path: + Path to the file containing replacements for obsolete PDBs. + shuffle_top_k_prefiltered: + Whether to uniformly shuffle the top k template hits before + parsing max_template_hits of them. Can be used to + approximate DeepMind's training-time template subsampling + scheme much more performantly. + treat_pdb_as_distillation: + Whether to assume that .pdb files in the data_dir are from + the self-distillation set (and should be subjected to + special distillation set preprocessing steps). + mode: + "train", "val", or "predict" + """ + super(OpenFoldSingleDataset, self).__init__() + self.data_dir = data_dir + self.alignment_dir = alignment_dir + self.config = config + self.treat_pdb_as_distillation = treat_pdb_as_distillation + self.mode = mode + self._output_raw = _output_raw + self._alignment_index = _alignment_index + + valid_modes = ["train", "eval", "predict"] + if(mode not in valid_modes): + raise ValueError(f'mode must be one of {valid_modes}') + + if(template_release_dates_cache_path is None): + logging.warning( + "Template release dates cache does not exist. Remember to run " + "scripts/generate_mmcif_cache.py before running OpenFold" + ) + + if(_alignment_index is not None): + self._chain_ids = list(_alignment_index.keys()) + elif(mapping_path is None): + self._chain_ids = list(os.listdir(alignment_dir)) + else: + with open(mapping_path, "r") as f: + self._chain_ids = [l.strip() for l in f.readlines()] + + self._chain_id_to_idx_dict = { + chain: i for i, chain in enumerate(self._chain_ids) + } + + template_featurizer = templates.TemplateHitFeaturizer( + mmcif_dir=template_mmcif_dir, + max_template_date=max_template_date, + max_hits=max_template_hits, + kalign_binary_path=kalign_binary_path, + release_dates_path=template_release_dates_cache_path, + obsolete_pdbs_path=obsolete_pdbs_file_path, + _shuffle_top_k_prefiltered=shuffle_top_k_prefiltered, + ) + + self.data_pipeline = data_pipeline.DataPipeline( + template_featurizer=template_featurizer, + ) + + if(not self._output_raw): + self.feature_pipeline = feature_pipeline.FeaturePipeline(config) + + def _parse_mmcif(self, path, file_id, chain_id, alignment_dir, _alignment_index): + with open(path, 'r') as f: + mmcif_string = f.read() + + mmcif_object = mmcif_parsing.parse( + file_id=file_id, mmcif_string=mmcif_string + ) + + # Crash if an error is encountered. Any parsing errors should have + # been dealt with at the alignment stage. + if(mmcif_object.mmcif_object is None): + raise list(mmcif_object.errors.values())[0] + + mmcif_object = mmcif_object.mmcif_object + + data = self.data_pipeline.process_mmcif( + mmcif=mmcif_object, + alignment_dir=alignment_dir, + chain_id=chain_id, + _alignment_index=_alignment_index + ) + + return data + + def chain_id_to_idx(self, chain_id): + return self._chain_id_to_idx_dict[chain_id] + + def idx_to_chain_id(self, idx): + return self._chain_ids[idx] + + def __getitem__(self, idx): + name = self.idx_to_chain_id(idx) + alignment_dir = os.path.join(self.alignment_dir, name) + + _alignment_index = None + if(self._alignment_index is not None): + alignment_dir = self.alignment_dir + _alignment_index = self._alignment_index[name] + + if(self.mode == 'train' or self.mode == 'eval'): + spl = name.rsplit('_', 1) + if(len(spl) == 2): + file_id, chain_id = spl + else: + file_id, = spl + chain_id = None + + path = os.path.join(self.data_dir, file_id) + if(os.path.exists(path + ".cif")): + data = self._parse_mmcif( + path + ".cif", file_id, chain_id, alignment_dir, _alignment_index, + ) + elif(os.path.exists(path + ".core")): + data = self.data_pipeline.process_core( + path + ".core", alignment_dir, _alignment_index, + ) + elif(os.path.exists(path + ".pdb")): + data = self.data_pipeline.process_pdb( + pdb_path=path + ".pdb", + alignment_dir=alignment_dir, + is_distillation=self.treat_pdb_as_distillation, + chain_id=chain_id, + _alignment_index=_alignment_index, + ) + else: + raise ValueError("Invalid file type") + else: + path = os.path.join(name, name + ".fasta") + data = self.data_pipeline.process_fasta( + fasta_path=path, + alignment_dir=alignment_dir, + _alignment_index=_alignment_index, + ) + + if(self._output_raw): + return data + + feats = self.feature_pipeline.process_features( + data, self.mode + ) + + return feats + + def __len__(self): + return len(self._chain_ids) + + +def deterministic_train_filter( + chain_data_cache_entry: Any, + max_resolution: float = 9., + max_single_aa_prop: float = 0.8, +) -> bool: + # Hard filters + resolution = chain_data_cache_entry.get("resolution", None) + if(resolution is not None and resolution > max_resolution): + return False + + seq = chain_data_cache_entry["seq"] + counts = {} + for aa in seq: + counts.setdefault(aa, 0) + counts[aa] += 1 + largest_aa_count = max(counts.values()) + largest_single_aa_prop = largest_aa_count / len(seq) + if(largest_single_aa_prop > max_single_aa_prop): + return False + + return True + + +def get_stochastic_train_filter_prob( + chain_data_cache_entry: Any, +) -> List[float]: + # Stochastic filters + probabilities = [] + + cluster_size = chain_data_cache_entry.get("cluster_size", None) + if(cluster_size is not None and cluster_size > 0): + probabilities.append(1 / cluster_size) + + chain_length = len(chain_data_cache_entry["seq"]) + probabilities.append((1 / 512) * (max(min(chain_length, 512), 256))) + + # Risk of underflow here? + out = 1 + for p in probabilities: + out *= p + + return out + + +class OpenFoldDataset(torch.utils.data.Dataset): + """ + Implements the stochastic filters applied during AlphaFold's training. + Because samples are selected from constituent datasets randomly, the + length of an OpenFoldFilteredDataset is arbitrary. Samples are selected + and filtered once at initialization. + """ + def __init__(self, + datasets: Sequence[OpenFoldSingleDataset], + probabilities: Sequence[int], + epoch_len: int, + chain_data_cache_paths: List[str], + generator: torch.Generator = None, + _roll_at_init: bool = True, + ): + self.datasets = datasets + self.probabilities = probabilities + self.epoch_len = epoch_len + self.generator = generator + + self.chain_data_caches = [] + for path in chain_data_cache_paths: + with open(path, "r") as fp: + self.chain_data_caches.append(json.load(fp)) + + def looped_shuffled_dataset_idx(dataset_len): + while True: + # Uniformly shuffle each dataset's indices + weights = [1. for _ in range(dataset_len)] + shuf = torch.multinomial( + torch.tensor(weights), + num_samples=dataset_len, + replacement=False, + generator=self.generator, + ) + for idx in shuf: + yield idx + + def looped_samples(dataset_idx): + max_cache_len = int(epoch_len * probabilities[dataset_idx]) + dataset = self.datasets[dataset_idx] + idx_iter = looped_shuffled_dataset_idx(len(dataset)) + chain_data_cache = self.chain_data_caches[dataset_idx] + while True: + weights = [] + idx = [] + for _ in range(max_cache_len): + candidate_idx = next(idx_iter) + chain_id = dataset.idx_to_chain_id(candidate_idx) + chain_data_cache_entry = chain_data_cache[chain_id] + if(not deterministic_train_filter(chain_data_cache_entry)): + continue + + p = get_stochastic_train_filter_prob( + chain_data_cache_entry, + ) + weights.append([1. - p, p]) + idx.append(candidate_idx) + + samples = torch.multinomial( + torch.tensor(weights), + num_samples=1, + generator=self.generator, + ) + samples = samples.squeeze() + + cache = [i for i, s in zip(idx, samples) if s] + + for datapoint_idx in cache: + yield datapoint_idx + + self._samples = [looped_samples(i) for i in range(len(self.datasets))] + + if(_roll_at_init): + self.reroll() + + def __getitem__(self, idx): + dataset_idx, datapoint_idx = self.datapoints[idx] + return self.datasets[dataset_idx][datapoint_idx] + + def __len__(self): + return self.epoch_len + + def reroll(self): + dataset_choices = torch.multinomial( + torch.tensor(self.probabilities), + num_samples=self.epoch_len, + replacement=True, + generator=self.generator, + ) + + self.datapoints = [] + for dataset_idx in dataset_choices: + samples = self._samples[dataset_idx] + datapoint_idx = next(samples) + self.datapoints.append((dataset_idx, datapoint_idx)) + + +class OpenFoldBatchCollator: + def __init__(self, config, stage="train"): + self.stage = stage + self.feature_pipeline = feature_pipeline.FeaturePipeline(config) + + def __call__(self, raw_prots): + processed_prots = [] + for prot in raw_prots: + features = self.feature_pipeline.process_features( + prot, self.stage + ) + processed_prots.append(features) + + stack_fn = partial(torch.stack, dim=0) + return dict_multimap(stack_fn, processed_prots) + + +class OpenFoldDataLoader(torch.utils.data.DataLoader): + def __init__(self, *args, config, stage="train", generator=None, **kwargs): + super().__init__(*args, **kwargs) + self.config = config + self.stage = stage + + if(generator is None): + generator = torch.Generator() + + self.generator = generator + self._prep_batch_properties_probs() + + def _prep_batch_properties_probs(self): + keyed_probs = [] + stage_cfg = self.config[self.stage] + + max_iters = self.config.common.max_recycling_iters + if(stage_cfg.supervised): + clamp_prob = self.config.supervised.clamp_prob + keyed_probs.append( + ("use_clamped_fape", [1 - clamp_prob, clamp_prob]) + ) + + if(stage_cfg.uniform_recycling): + recycling_probs = [ + 1. / (max_iters + 1) for _ in range(max_iters + 1) + ] + else: + recycling_probs = [ + 0. for _ in range(max_iters + 1) + ] + recycling_probs[-1] = 1. + + keyed_probs.append( + ("no_recycling_iters", recycling_probs) + ) + + keys, probs = zip(*keyed_probs) + max_len = max([len(p) for p in probs]) + padding = [[0.] * (max_len - len(p)) for p in probs] + + self.prop_keys = keys + self.prop_probs_tensor = torch.tensor( + [p + pad for p, pad in zip(probs, padding)], + dtype=torch.float32, + ) + + def _add_batch_properties(self, batch): + samples = torch.multinomial( + self.prop_probs_tensor, + num_samples=1, # 1 per row + replacement=True, + generator=self.generator + ) + + aatype = batch["aatype"] + batch_dims = aatype.shape[:-2] + recycling_dim = aatype.shape[-1] + no_recycling = recycling_dim + for i, key in enumerate(self.prop_keys): + sample = int(samples[i][0]) + sample_tensor = torch.tensor( + sample, + device=aatype.device, + requires_grad=False + ) + orig_shape = sample_tensor.shape + sample_tensor = sample_tensor.view( + (1,) * len(batch_dims) + sample_tensor.shape + (1,) + ) + sample_tensor = sample_tensor.expand( + batch_dims + orig_shape + (recycling_dim,) + ) + batch[key] = sample_tensor + + if(key == "no_recycling_iters"): + no_recycling = sample + + resample_recycling = lambda t: t[..., :no_recycling + 1] + batch = tensor_tree_map(resample_recycling, batch) + + return batch + + def __iter__(self): + it = super().__iter__() + + def _batch_prop_gen(iterator): + for batch in iterator: + yield self._add_batch_properties(batch) + + return _batch_prop_gen(it) + + +class OpenFoldDataModule(pl.LightningDataModule): + def __init__(self, + config: mlc.ConfigDict, + template_mmcif_dir: str, + max_template_date: str, + train_data_dir: Optional[str] = None, + train_alignment_dir: Optional[str] = None, + train_chain_data_cache_path: Optional[str] = None, + distillation_data_dir: Optional[str] = None, + distillation_alignment_dir: Optional[str] = None, + distillation_chain_data_cache_path: Optional[str] = None, + val_data_dir: Optional[str] = None, + val_alignment_dir: Optional[str] = None, + predict_data_dir: Optional[str] = None, + predict_alignment_dir: Optional[str] = None, + kalign_binary_path: str = '/usr/bin/kalign', + train_mapping_path: Optional[str] = None, + distillation_mapping_path: Optional[str] = None, + obsolete_pdbs_file_path: Optional[str] = None, + template_release_dates_cache_path: Optional[str] = None, + batch_seed: Optional[int] = None, + train_epoch_len: int = 50000, + _alignment_index_path: Optional[str] = None, + **kwargs + ): + super(OpenFoldDataModule, self).__init__() + + self.config = config + self.template_mmcif_dir = template_mmcif_dir + self.max_template_date = max_template_date + self.train_data_dir = train_data_dir + self.train_alignment_dir = train_alignment_dir + self.train_chain_data_cache_path = train_chain_data_cache_path + self.distillation_data_dir = distillation_data_dir + self.distillation_alignment_dir = distillation_alignment_dir + self.distillation_chain_data_cache_path = ( + distillation_chain_data_cache_path + ) + self.val_data_dir = val_data_dir + self.val_alignment_dir = val_alignment_dir + self.predict_data_dir = predict_data_dir + self.predict_alignment_dir = predict_alignment_dir + self.kalign_binary_path = kalign_binary_path + self.train_mapping_path = train_mapping_path + self.distillation_mapping_path = distillation_mapping_path + self.template_release_dates_cache_path = ( + template_release_dates_cache_path + ) + self.obsolete_pdbs_file_path = obsolete_pdbs_file_path + self.batch_seed = batch_seed + self.train_epoch_len = train_epoch_len + + if(self.train_data_dir is None and self.predict_data_dir is None): + raise ValueError( + 'At least one of train_data_dir or predict_data_dir must be ' + 'specified' + ) + + self.training_mode = self.train_data_dir is not None + + if(self.training_mode and train_alignment_dir is None): + raise ValueError( + 'In training mode, train_alignment_dir must be specified' + ) + elif(not self.training_mode and predict_alignment_dir is None): + raise ValueError( + 'In inference mode, predict_alignment_dir must be specified' + ) + elif(val_data_dir is not None and val_alignment_dir is None): + raise ValueError( + 'If val_data_dir is specified, val_alignment_dir must ' + 'be specified as well' + ) + + # An ad-hoc measure for our particular filesystem restrictions + self._alignment_index = None + if(_alignment_index_path is not None): + with open(_alignment_index_path, "r") as fp: + self._alignment_index = json.load(fp) + + def setup(self): + # Most of the arguments are the same for the three datasets + dataset_gen = partial(OpenFoldSingleDataset, + template_mmcif_dir=self.template_mmcif_dir, + max_template_date=self.max_template_date, + config=self.config, + kalign_binary_path=self.kalign_binary_path, + template_release_dates_cache_path= + self.template_release_dates_cache_path, + obsolete_pdbs_file_path= + self.obsolete_pdbs_file_path, + ) + + if(self.training_mode): + train_dataset = dataset_gen( + data_dir=self.train_data_dir, + alignment_dir=self.train_alignment_dir, + mapping_path=self.train_mapping_path, + max_template_hits=self.config.train.max_template_hits, + shuffle_top_k_prefiltered= + self.config.train.shuffle_top_k_prefiltered, + treat_pdb_as_distillation=False, + mode="train", + _output_raw=True, + _alignment_index=self._alignment_index, + ) + + distillation_dataset = None + if(self.distillation_data_dir is not None): + distillation_dataset = dataset_gen( + data_dir=self.distillation_data_dir, + alignment_dir=self.distillation_alignment_dir, + mapping_path=self.distillation_mapping_path, + max_template_hits=self.train.max_template_hits, + treat_pdb_as_distillation=True, + mode="train", + _output_raw=True, + ) + + d_prob = self.config.train.distillation_prob + + if(distillation_dataset is not None): + datasets = [train_dataset, distillation_dataset] + d_prob = self.config.train.distillation_prob + probabilities = [1 - d_prob, d_prob] + chain_data_cache_paths = [ + self.train_chain_data_cache_path, + self.distillation_chain_data_cache_path, + ] + else: + datasets = [train_dataset] + probabilities = [1.] + chain_data_cache_paths = [ + self.train_chain_data_cache_path, + ] + + self.train_dataset = OpenFoldDataset( + datasets=datasets, + probabilities=probabilities, + epoch_len=self.train_epoch_len, + chain_data_cache_paths=chain_data_cache_paths, + _roll_at_init=False, + ) + + if(self.val_data_dir is not None): + self.eval_dataset = dataset_gen( + data_dir=self.val_data_dir, + alignment_dir=self.val_alignment_dir, + mapping_path=None, + max_template_hits=self.config.eval.max_template_hits, + mode="eval", + _output_raw=True, + ) + else: + self.eval_dataset = None + else: + self.predict_dataset = dataset_gen( + data_dir=self.predict_data_dir, + alignment_dir=self.predict_alignment_dir, + mapping_path=None, + max_template_hits=self.config.predict.max_template_hits, + mode="predict", + ) + + def _gen_dataloader(self, stage): + generator = torch.Generator() + if(self.batch_seed is not None): + generator = generator.manual_seed(self.batch_seed) + + dataset = None + if(stage == "train"): + dataset = self.train_dataset + + # Filter the dataset, if necessary + dataset.reroll() + elif(stage == "eval"): + dataset = self.eval_dataset + elif(stage == "predict"): + dataset = self.predict_dataset + else: + raise ValueError("Invalid stage") + + batch_collator = OpenFoldBatchCollator(self.config, stage) + + dl = OpenFoldDataLoader( + dataset, + config=self.config, + stage=stage, + generator=generator, + batch_size=self.config.data_module.data_loaders.batch_size, + num_workers=self.config.data_module.data_loaders.num_workers, + collate_fn=batch_collator, + ) + + return dl + + def train_dataloader(self): + return self._gen_dataloader("train") + + def val_dataloader(self): + if(self.eval_dataset is not None): + return self._gen_dataloader("eval") + return None + + def predict_dataloader(self): + return self._gen_dataloader("predict") + + +class DummyDataset(torch.utils.data.Dataset): + def __init__(self, batch_path): + with open(batch_path, "rb") as f: + self.batch = pickle.load(f) + + def __getitem__(self, idx): + return copy.deepcopy(self.batch) + + def __len__(self): + return 1000 + + +class DummyDataLoader(pl.LightningDataModule): + def __init__(self, batch_path): + super().__init__() + self.dataset = DummyDataset(batch_path) + + def train_dataloader(self): + return torch.utils.data.DataLoader(self.dataset) diff --git a/gafl/openfold/data/data_pipeline.py b/gafl/openfold/data/data_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..eb6419b7e1c48679005812cb522078f740978239 --- /dev/null +++ b/gafl/openfold/data/data_pipeline.py @@ -0,0 +1,678 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import datetime +from multiprocessing import cpu_count +from typing import Mapping, Optional, Sequence, Any + +import numpy as np + +from openfold.data import templates, parsers, mmcif_parsing +from openfold.data.tools import jackhmmer, hhblits, hhsearch +from openfold.data.tools.utils import to_date +from openfold.np import residue_constants, protein + + +FeatureDict = Mapping[str, np.ndarray] + +def empty_template_feats(n_res) -> FeatureDict: + return { + "template_aatype": np.zeros((0, n_res)).astype(np.int64), + "template_all_atom_positions": + np.zeros((0, n_res, 37, 3)).astype(np.float32), + "template_sum_probs": np.zeros((0, 1)).astype(np.float32), + "template_all_atom_mask": np.zeros((0, n_res, 37)).astype(np.float32), + } + + +def make_template_features( + input_sequence: str, + hits: Sequence[Any], + template_featurizer: Any, + query_pdb_code: Optional[str] = None, + query_release_date: Optional[str] = None, +) -> FeatureDict: + hits_cat = sum(hits.values(), []) + if(len(hits_cat) == 0 or template_featurizer is None): + template_features = empty_template_feats(len(input_sequence)) + else: + templates_result = template_featurizer.get_templates( + query_sequence=input_sequence, + query_pdb_code=query_pdb_code, + query_release_date=query_release_date, + hits=hits_cat, + ) + template_features = templates_result.features + + # The template featurizer doesn't format empty template features + # properly. This is a quick fix. + if(template_features["template_aatype"].shape[0] == 0): + template_features = empty_template_feats(len(input_sequence)) + + return template_features + + +def make_sequence_features( + sequence: str, description: str, num_res: int +) -> FeatureDict: + """Construct a feature dict of sequence features.""" + features = {} + features["aatype"] = residue_constants.sequence_to_onehot( + sequence=sequence, + mapping=residue_constants.restype_order_with_x, + map_unknown_to_x=True, + ) + features["between_segment_residues"] = np.zeros((num_res,), dtype=int) + features["domain_name"] = np.array( + [description.encode("utf-8")], dtype=np.object_ + ) + features["residue_index"] = np.array(range(num_res), dtype=int) + features["seq_length"] = np.array([num_res] * num_res, dtype=int) + features["sequence"] = np.array( + [sequence.encode("utf-8")], dtype=np.object_ + ) + return features + + +def make_mmcif_features( + mmcif_object: mmcif_parsing.MmcifObject, chain_id: str +) -> FeatureDict: + input_sequence = mmcif_object.chain_to_seqres[chain_id] + description = "_".join([mmcif_object.file_id, chain_id]) + num_res = len(input_sequence) + + mmcif_feats = {} + + mmcif_feats.update( + make_sequence_features( + sequence=input_sequence, + description=description, + num_res=num_res, + ) + ) + + all_atom_positions, all_atom_mask = mmcif_parsing.get_atom_coords( + mmcif_object=mmcif_object, chain_id=chain_id + ) + mmcif_feats["all_atom_positions"] = all_atom_positions + mmcif_feats["all_atom_mask"] = all_atom_mask + + mmcif_feats["resolution"] = np.array( + [mmcif_object.header["resolution"]], dtype=np.float32 + ) + + mmcif_feats["release_date"] = np.array( + [mmcif_object.header["release_date"].encode("utf-8")], dtype=np.object_ + ) + + mmcif_feats["is_distillation"] = np.array(0., dtype=np.float32) + + return mmcif_feats + + +def _aatype_to_str_sequence(aatype): + return ''.join([ + residue_constants.restypes_with_x[aatype[i]] + for i in range(len(aatype)) + ]) + + +def make_protein_features( + protein_object: protein.Protein, + description: str, + _is_distillation: bool = False, +) -> FeatureDict: + pdb_feats = {} + aatype = protein_object.aatype + sequence = _aatype_to_str_sequence(aatype) + pdb_feats.update( + make_sequence_features( + sequence=sequence, + description=description, + num_res=len(protein_object.aatype), + ) + ) + + all_atom_positions = protein_object.atom_positions + all_atom_mask = protein_object.atom_mask + + pdb_feats["all_atom_positions"] = all_atom_positions.astype(np.float32) + pdb_feats["all_atom_mask"] = all_atom_mask.astype(np.float32) + + pdb_feats["resolution"] = np.array([0.]).astype(np.float32) + pdb_feats["is_distillation"] = np.array( + 1. if _is_distillation else 0. + ).astype(np.float32) + + return pdb_feats + + +def make_pdb_features( + protein_object: protein.Protein, + description: str, + confidence_threshold: float = 0.5, + is_distillation: bool = True, +) -> FeatureDict: + pdb_feats = make_protein_features( + protein_object, description, _is_distillation=True + ) + + if(is_distillation): + high_confidence = protein_object.b_factors > confidence_threshold + high_confidence = np.any(high_confidence, axis=-1) + for i, confident in enumerate(high_confidence): + if(not confident): + pdb_feats["all_atom_mask"][i] = 0 + + return pdb_feats + + +def make_msa_features( + msas: Sequence[Sequence[str]], + deletion_matrices: Sequence[parsers.DeletionMatrix], +) -> FeatureDict: + """Constructs a feature dict of MSA features.""" + if not msas: + raise ValueError("At least one MSA must be provided.") + + int_msa = [] + deletion_matrix = [] + seen_sequences = set() + for msa_index, msa in enumerate(msas): + if not msa: + raise ValueError( + f"MSA {msa_index} must contain at least one sequence." + ) + for sequence_index, sequence in enumerate(msa): + if sequence in seen_sequences: + continue + seen_sequences.add(sequence) + int_msa.append( + [residue_constants.HHBLITS_AA_TO_ID[res] for res in sequence] + ) + deletion_matrix.append(deletion_matrices[msa_index][sequence_index]) + + num_res = len(msas[0][0]) + num_alignments = len(int_msa) + features = {} + features["deletion_matrix_int"] = np.array(deletion_matrix, dtype=int) + features["msa"] = np.array(int_msa, dtype=int) + features["num_alignments"] = np.array( + [num_alignments] * num_res, dtype=int + ) + return features + + +class AlignmentRunner: + """Runs alignment tools and saves the results""" + def __init__( + self, + jackhmmer_binary_path: Optional[str] = None, + hhblits_binary_path: Optional[str] = None, + hhsearch_binary_path: Optional[str] = None, + uniref90_database_path: Optional[str] = None, + mgnify_database_path: Optional[str] = None, + bfd_database_path: Optional[str] = None, + uniclust30_database_path: Optional[str] = None, + pdb70_database_path: Optional[str] = None, + use_small_bfd: Optional[bool] = None, + no_cpus: Optional[int] = None, + uniref_max_hits: int = 10000, + mgnify_max_hits: int = 5000, + ): + """ + Args: + jackhmmer_binary_path: + Path to jackhmmer binary + hhblits_binary_path: + Path to hhblits binary + hhsearch_binary_path: + Path to hhsearch binary + uniref90_database_path: + Path to uniref90 database. If provided, jackhmmer_binary_path + must also be provided + mgnify_database_path: + Path to mgnify database. If provided, jackhmmer_binary_path + must also be provided + bfd_database_path: + Path to BFD database. Depending on the value of use_small_bfd, + one of hhblits_binary_path or jackhmmer_binary_path must be + provided. + uniclust30_database_path: + Path to uniclust30. Searched alongside BFD if use_small_bfd is + false. + pdb70_database_path: + Path to pdb70 database. + use_small_bfd: + Whether to search the BFD database alone with jackhmmer or + in conjunction with uniclust30 with hhblits. + no_cpus: + The number of CPUs available for alignment. By default, all + CPUs are used. + uniref_max_hits: + Max number of uniref hits + mgnify_max_hits: + Max number of mgnify hits + """ + db_map = { + "jackhmmer": { + "binary": jackhmmer_binary_path, + "dbs": [ + uniref90_database_path, + mgnify_database_path, + bfd_database_path if use_small_bfd else None, + ], + }, + "hhblits": { + "binary": hhblits_binary_path, + "dbs": [ + bfd_database_path if not use_small_bfd else None, + ], + }, + "hhsearch": { + "binary": hhsearch_binary_path, + "dbs": [ + pdb70_database_path, + ], + }, + } + + for name, dic in db_map.items(): + binary, dbs = dic["binary"], dic["dbs"] + if(binary is None and not all([x is None for x in dbs])): + raise ValueError( + f"{name} DBs provided but {name} binary is None" + ) + + if(not all([x is None for x in db_map["hhsearch"]["dbs"]]) + and uniref90_database_path is None): + raise ValueError( + """uniref90_database_path must be specified in order to perform + template search""" + ) + + self.uniref_max_hits = uniref_max_hits + self.mgnify_max_hits = mgnify_max_hits + self.use_small_bfd = use_small_bfd + + if(no_cpus is None): + no_cpus = cpu_count() + + self.jackhmmer_uniref90_runner = None + if(jackhmmer_binary_path is not None and + uniref90_database_path is not None + ): + self.jackhmmer_uniref90_runner = jackhmmer.Jackhmmer( + binary_path=jackhmmer_binary_path, + database_path=uniref90_database_path, + n_cpu=no_cpus, + ) + + self.jackhmmer_small_bfd_runner = None + self.hhblits_bfd_uniclust_runner = None + if(bfd_database_path is not None): + if use_small_bfd: + self.jackhmmer_small_bfd_runner = jackhmmer.Jackhmmer( + binary_path=jackhmmer_binary_path, + database_path=bfd_database_path, + n_cpu=no_cpus, + ) + else: + dbs = [bfd_database_path] + if(uniclust30_database_path is not None): + dbs.append(uniclust30_database_path) + self.hhblits_bfd_uniclust_runner = hhblits.HHBlits( + binary_path=hhblits_binary_path, + databases=dbs, + n_cpu=no_cpus, + ) + + self.jackhmmer_mgnify_runner = None + if(mgnify_database_path is not None): + self.jackhmmer_mgnify_runner = jackhmmer.Jackhmmer( + binary_path=jackhmmer_binary_path, + database_path=mgnify_database_path, + n_cpu=no_cpus, + ) + + self.hhsearch_pdb70_runner = None + if(pdb70_database_path is not None): + self.hhsearch_pdb70_runner = hhsearch.HHSearch( + binary_path=hhsearch_binary_path, + databases=[pdb70_database_path], + n_cpu=no_cpus, + ) + + def run( + self, + fasta_path: str, + output_dir: str, + ): + """Runs alignment tools on a sequence""" + if(self.jackhmmer_uniref90_runner is not None): + jackhmmer_uniref90_result = self.jackhmmer_uniref90_runner.query( + fasta_path + )[0] + uniref90_msa_as_a3m = parsers.convert_stockholm_to_a3m( + jackhmmer_uniref90_result["sto"], + max_sequences=self.uniref_max_hits + ) + uniref90_out_path = os.path.join(output_dir, "uniref90_hits.a3m") + with open(uniref90_out_path, "w") as f: + f.write(uniref90_msa_as_a3m) + + if(self.hhsearch_pdb70_runner is not None): + hhsearch_result = self.hhsearch_pdb70_runner.query( + uniref90_msa_as_a3m + ) + pdb70_out_path = os.path.join(output_dir, "pdb70_hits.hhr") + with open(pdb70_out_path, "w") as f: + f.write(hhsearch_result) + + if(self.jackhmmer_mgnify_runner is not None): + jackhmmer_mgnify_result = self.jackhmmer_mgnify_runner.query( + fasta_path + )[0] + mgnify_msa_as_a3m = parsers.convert_stockholm_to_a3m( + jackhmmer_mgnify_result["sto"], + max_sequences=self.mgnify_max_hits + ) + mgnify_out_path = os.path.join(output_dir, "mgnify_hits.a3m") + with open(mgnify_out_path, "w") as f: + f.write(mgnify_msa_as_a3m) + + if(self.use_small_bfd and self.jackhmmer_small_bfd_runner is not None): + jackhmmer_small_bfd_result = self.jackhmmer_small_bfd_runner.query( + fasta_path + )[0] + bfd_out_path = os.path.join(output_dir, "small_bfd_hits.sto") + with open(bfd_out_path, "w") as f: + f.write(jackhmmer_small_bfd_result["sto"]) + elif(self.hhblits_bfd_uniclust_runner is not None): + hhblits_bfd_uniclust_result = ( + self.hhblits_bfd_uniclust_runner.query(fasta_path) + ) + if output_dir is not None: + bfd_out_path = os.path.join(output_dir, "bfd_uniclust_hits.a3m") + with open(bfd_out_path, "w") as f: + f.write(hhblits_bfd_uniclust_result["a3m"]) + + +class DataPipeline: + """Assembles input features.""" + def __init__( + self, + template_featurizer: Optional[templates.TemplateHitFeaturizer], + ): + self.template_featurizer = template_featurizer + + def _parse_msa_data( + self, + alignment_dir: str, + _alignment_index: Optional[Any] = None, + ) -> Mapping[str, Any]: + msa_data = {} + + if(_alignment_index is not None): + fp = open(os.path.join(alignment_dir, _alignment_index["db"]), "rb") + + def read_msa(start, size): + fp.seek(start) + msa = fp.read(size).decode("utf-8") + return msa + + for (name, start, size) in _alignment_index["files"]: + ext = os.path.splitext(name)[-1] + + if(ext == ".a3m"): + msa, deletion_matrix = parsers.parse_a3m( + read_msa(start, size) + ) + data = {"msa": msa, "deletion_matrix": deletion_matrix} + elif(ext == ".sto"): + msa, deletion_matrix, _ = parsers.parse_stockholm( + read_msa(start, size) + ) + data = {"msa": msa, "deletion_matrix": deletion_matrix} + else: + continue + + msa_data[name] = data + + fp.close() + else: + for f in os.listdir(alignment_dir): + path = os.path.join(alignment_dir, f) + ext = os.path.splitext(f)[-1] + + if(ext == ".a3m"): + with open(path, "r") as fp: + msa, deletion_matrix = parsers.parse_a3m(fp.read()) + data = {"msa": msa, "deletion_matrix": deletion_matrix} + elif(ext == ".sto"): + with open(path, "r") as fp: + msa, deletion_matrix, _ = parsers.parse_stockholm( + fp.read() + ) + data = {"msa": msa, "deletion_matrix": deletion_matrix} + else: + continue + + msa_data[f] = data + + return msa_data + + def _parse_template_hits( + self, + alignment_dir: str, + _alignment_index: Optional[Any] = None + ) -> Mapping[str, Any]: + all_hits = {} + if(_alignment_index is not None): + fp = open(os.path.join(alignment_dir, _alignment_index["db"]), 'rb') + + def read_template(start, size): + fp.seek(start) + return fp.read(size).decode("utf-8") + + for (name, start, size) in _alignment_index["files"]: + ext = os.path.splitext(name)[-1] + + if(ext == ".hhr"): + hits = parsers.parse_hhr(read_template(start, size)) + all_hits[name] = hits + + fp.close() + else: + for f in os.listdir(alignment_dir): + path = os.path.join(alignment_dir, f) + ext = os.path.splitext(f)[-1] + + if(ext == ".hhr"): + with open(path, "r") as fp: + hits = parsers.parse_hhr(fp.read()) + all_hits[f] = hits + + return all_hits + + def _process_msa_feats( + self, + alignment_dir: str, + input_sequence: Optional[str] = None, + _alignment_index: Optional[str] = None + ) -> Mapping[str, Any]: + msa_data = self._parse_msa_data(alignment_dir, _alignment_index) + + if(len(msa_data) == 0): + if(input_sequence is None): + raise ValueError( + """ + If the alignment dir contains no MSAs, an input sequence + must be provided. + """ + ) + msa_data["dummy"] = { + "msa": [input_sequence], + "deletion_matrix": [[0 for _ in input_sequence]], + } + + msas, deletion_matrices = zip(*[ + (v["msa"], v["deletion_matrix"]) for v in msa_data.values() + ]) + + msa_features = make_msa_features( + msas=msas, + deletion_matrices=deletion_matrices, + ) + + return msa_features + + def process_fasta( + self, + fasta_path: str, + alignment_dir: str, + _alignment_index: Optional[str] = None, + ) -> FeatureDict: + """Assembles features for a single sequence in a FASTA file""" + with open(fasta_path) as f: + fasta_str = f.read() + input_seqs, input_descs = parsers.parse_fasta(fasta_str) + if len(input_seqs) != 1: + raise ValueError( + f"More than one input sequence found in {fasta_path}." + ) + input_sequence = input_seqs[0] + input_description = input_descs[0] + num_res = len(input_sequence) + + hits = self._parse_template_hits(alignment_dir, _alignment_index) + template_features = make_template_features( + input_sequence, + hits, + self.template_featurizer, + ) + + sequence_features = make_sequence_features( + sequence=input_sequence, + description=input_description, + num_res=num_res, + ) + + msa_features = self._process_msa_feats(alignment_dir, input_sequence, _alignment_index) + + return { + **sequence_features, + **msa_features, + **template_features + } + + def process_mmcif( + self, + mmcif: mmcif_parsing.MmcifObject, # parsing is expensive, so no path + alignment_dir: str, + chain_id: Optional[str] = None, + _alignment_index: Optional[str] = None, + ) -> FeatureDict: + """ + Assembles features for a specific chain in an mmCIF object. + + If chain_id is None, it is assumed that there is only one chain + in the object. Otherwise, a ValueError is thrown. + """ + if chain_id is None: + chains = mmcif.structure.get_chains() + chain = next(chains, None) + if chain is None: + raise ValueError("No chains in mmCIF file") + chain_id = chain.id + + mmcif_feats = make_mmcif_features(mmcif, chain_id) + + input_sequence = mmcif.chain_to_seqres[chain_id] + hits = self._parse_template_hits(alignment_dir, _alignment_index) + template_features = make_template_features( + input_sequence, + hits, + self.template_featurizer, + query_release_date=to_date(mmcif.header["release_date"]) + ) + + msa_features = self._process_msa_feats(alignment_dir, input_sequence, _alignment_index) + + return {**mmcif_feats, **template_features, **msa_features} + + def process_pdb( + self, + pdb_path: str, + alignment_dir: str, + is_distillation: bool = True, + chain_id: Optional[str] = None, + _alignment_index: Optional[str] = None, + ) -> FeatureDict: + """ + Assembles features for a protein in a PDB file. + """ + with open(pdb_path, 'r') as f: + pdb_str = f.read() + + protein_object = protein.from_pdb_string(pdb_str, chain_id) + input_sequence = _aatype_to_str_sequence(protein_object.aatype) + description = os.path.splitext(os.path.basename(pdb_path))[0].upper() + pdb_feats = make_pdb_features( + protein_object, + description, + is_distillation + ) + + hits = self._parse_template_hits(alignment_dir, _alignment_index) + template_features = make_template_features( + input_sequence, + hits, + self.template_featurizer, + ) + + msa_features = self._process_msa_feats(alignment_dir, input_sequence, _alignment_index) + + return {**pdb_feats, **template_features, **msa_features} + + def process_core( + self, + core_path: str, + alignment_dir: str, + _alignment_index: Optional[str] = None, + ) -> FeatureDict: + """ + Assembles features for a protein in a ProteinNet .core file. + """ + with open(core_path, 'r') as f: + core_str = f.read() + + protein_object = protein.from_proteinnet_string(core_str) + input_sequence = _aatype_to_str_sequence(protein_object.aatype) + description = os.path.splitext(os.path.basename(core_path))[0].upper() + core_feats = make_protein_features(protein_object, description) + + hits = self._parse_template_hits(alignment_dir, _alignment_index) + template_features = make_template_features( + input_sequence, + hits, + self.template_featurizer, + ) + + msa_features = self._process_msa_feats(alignment_dir, input_sequence) + + return {**core_feats, **template_features, **msa_features} + diff --git a/gafl/openfold/data/data_transforms.py b/gafl/openfold/data/data_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5b19f4c74b035563944894984de59214bb48dd --- /dev/null +++ b/gafl/openfold/data/data_transforms.py @@ -0,0 +1,1191 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import itertools +from functools import reduce, wraps +from operator import add + +import numpy as np +import torch + +from openfold.config import NUM_RES, NUM_EXTRA_SEQ, NUM_TEMPLATES, NUM_MSA_SEQ +from openfold.np import residue_constants as rc +from openfold.utils.rigid_utils import Rotation, Rigid +from openfold.utils.tensor_utils import ( + tree_map, + tensor_tree_map, + batched_gather, +) + + +MSA_FEATURE_NAMES = [ + "msa", + "deletion_matrix", + "msa_mask", + "msa_row_mask", + "bert_mask", + "true_msa", +] + + +def cast_to_64bit_ints(protein): + # We keep all ints as int64 + for k, v in protein.items(): + if v.dtype == torch.int32: + protein[k] = v.type(torch.int64) + + return protein + + +def make_one_hot(x, num_classes): + x_one_hot = torch.zeros(*x.shape, num_classes) + x_one_hot.scatter_(-1, x.unsqueeze(-1), 1) + return x_one_hot + + +def make_seq_mask(protein): + protein["seq_mask"] = torch.ones( + protein["aatype"].shape, dtype=torch.float32 + ) + return protein + + +def make_template_mask(protein): + protein["template_mask"] = torch.ones( + protein["template_aatype"].shape[0], dtype=torch.float32 + ) + return protein + + +def curry1(f): + """Supply all arguments but the first.""" + @wraps(f) + def fc(*args, **kwargs): + return lambda x: f(x, *args, **kwargs) + + return fc + + +def make_all_atom_aatype(protein): + protein["all_atom_aatype"] = protein["aatype"] + return protein + + +def fix_templates_aatype(protein): + # Map one-hot to indices + num_templates = protein["template_aatype"].shape[0] + if(num_templates > 0): + protein["template_aatype"] = torch.argmax( + protein["template_aatype"], dim=-1 + ) + # Map hhsearch-aatype to our aatype. + new_order_list = rc.MAP_HHBLITS_AATYPE_TO_OUR_AATYPE + new_order = torch.tensor(new_order_list, dtype=torch.int64).expand( + num_templates, -1 + ) + protein["template_aatype"] = torch.gather( + new_order, 1, index=protein["template_aatype"] + ) + + return protein + + +def correct_msa_restypes(protein): + """Correct MSA restype to have the same order as rc.""" + new_order_list = rc.MAP_HHBLITS_AATYPE_TO_OUR_AATYPE + new_order = torch.tensor( + [new_order_list] * protein["msa"].shape[1], dtype=protein["msa"].dtype + ).transpose(0, 1) + protein["msa"] = torch.gather(new_order, 0, protein["msa"]) + + perm_matrix = np.zeros((22, 22), dtype=np.float32) + perm_matrix[range(len(new_order_list)), new_order_list] = 1.0 + + for k in protein: + if "profile" in k: + num_dim = protein[k].shape.as_list()[-1] + assert num_dim in [ + 20, + 21, + 22, + ], "num_dim for %s out of expected range: %s" % (k, num_dim) + protein[k] = torch.dot(protein[k], perm_matrix[:num_dim, :num_dim]) + + return protein + + +def squeeze_features(protein): + """Remove singleton and repeated dimensions in protein features.""" + protein["aatype"] = torch.argmax(protein["aatype"], dim=-1) + for k in [ + "domain_name", + "msa", + "num_alignments", + "seq_length", + "sequence", + "superfamily", + "deletion_matrix", + "resolution", + "between_segment_residues", + "residue_index", + "template_all_atom_mask", + ]: + if k in protein: + final_dim = protein[k].shape[-1] + if isinstance(final_dim, int) and final_dim == 1: + if torch.is_tensor(protein[k]): + protein[k] = torch.squeeze(protein[k], dim=-1) + else: + protein[k] = np.squeeze(protein[k], axis=-1) + + for k in ["seq_length", "num_alignments"]: + if k in protein: + protein[k] = protein[k][0] + + return protein + + +@curry1 +def randomly_replace_msa_with_unknown(protein, replace_proportion): + """Replace a portion of the MSA with 'X'.""" + msa_mask = torch.rand(protein["msa"].shape) < replace_proportion + x_idx = 20 + gap_idx = 21 + msa_mask = torch.logical_and(msa_mask, protein["msa"] != gap_idx) + protein["msa"] = torch.where( + msa_mask, + torch.ones_like(protein["msa"]) * x_idx, + protein["msa"] + ) + aatype_mask = torch.rand(protein["aatype"].shape) < replace_proportion + + protein["aatype"] = torch.where( + aatype_mask, + torch.ones_like(protein["aatype"]) * x_idx, + protein["aatype"], + ) + return protein + + +@curry1 +def sample_msa(protein, max_seq, keep_extra, seed=None): + """Sample MSA randomly, remaining sequences are stored are stored as `extra_*`.""" + num_seq = protein["msa"].shape[0] + g = torch.Generator(device=protein["msa"].device) + if seed is not None: + g.manual_seed(seed) + shuffled = torch.randperm(num_seq - 1, generator=g) + 1 + index_order = torch.cat((torch.tensor([0]), shuffled), dim=0) + num_sel = min(max_seq, num_seq) + sel_seq, not_sel_seq = torch.split( + index_order, [num_sel, num_seq - num_sel] + ) + + for k in MSA_FEATURE_NAMES: + if k in protein: + if keep_extra: + protein["extra_" + k] = torch.index_select( + protein[k], 0, not_sel_seq + ) + protein[k] = torch.index_select(protein[k], 0, sel_seq) + + return protein + + +@curry1 +def add_distillation_flag(protein, distillation): + protein['is_distillation'] = distillation + return protein + +@curry1 +def sample_msa_distillation(protein, max_seq): + if(protein["is_distillation"] == 1): + protein = sample_msa(max_seq, keep_extra=False)(protein) + return protein + + +@curry1 +def crop_extra_msa(protein, max_extra_msa): + num_seq = protein["extra_msa"].shape[0] + num_sel = min(max_extra_msa, num_seq) + select_indices = torch.randperm(num_seq)[:num_sel] + for k in MSA_FEATURE_NAMES: + if "extra_" + k in protein: + protein["extra_" + k] = torch.index_select( + protein["extra_" + k], 0, select_indices + ) + + return protein + + +def delete_extra_msa(protein): + for k in MSA_FEATURE_NAMES: + if "extra_" + k in protein: + del protein["extra_" + k] + return protein + + +# Not used in inference +@curry1 +def block_delete_msa(protein, config): + num_seq = protein["msa"].shape[0] + block_num_seq = torch.floor( + torch.tensor(num_seq, dtype=torch.float32) + * config.msa_fraction_per_block + ).to(torch.int32) + + if config.randomize_num_blocks: + nb = torch.distributions.uniform.Uniform( + 0, config.num_blocks + 1 + ).sample() + else: + nb = config.num_blocks + + del_block_starts = torch.distributions.Uniform(0, num_seq).sample(nb) + del_blocks = del_block_starts[:, None] + torch.range(block_num_seq) + del_blocks = torch.clip(del_blocks, 0, num_seq - 1) + del_indices = torch.unique(torch.sort(torch.reshape(del_blocks, [-1])))[0] + + # Make sure we keep the original sequence + combined = torch.cat((torch.range(1, num_seq)[None], del_indices[None])) + uniques, counts = combined.unique(return_counts=True) + difference = uniques[counts == 1] + intersection = uniques[counts > 1] + keep_indices = torch.squeeze(difference, 0) + + for k in MSA_FEATURE_NAMES: + if k in protein: + protein[k] = torch.gather(protein[k], keep_indices) + + return protein + + +@curry1 +def nearest_neighbor_clusters(protein, gap_agreement_weight=0.0): + weights = torch.cat( + [torch.ones(21), gap_agreement_weight * torch.ones(1), torch.zeros(1)], + 0, + ) + + # Make agreement score as weighted Hamming distance + msa_one_hot = make_one_hot(protein["msa"], 23) + sample_one_hot = protein["msa_mask"][:, :, None] * msa_one_hot + extra_msa_one_hot = make_one_hot(protein["extra_msa"], 23) + extra_one_hot = protein["extra_msa_mask"][:, :, None] * extra_msa_one_hot + + num_seq, num_res, _ = sample_one_hot.shape + extra_num_seq, _, _ = extra_one_hot.shape + + # Compute tf.einsum('mrc,nrc,c->mn', sample_one_hot, extra_one_hot, weights) + # in an optimized fashion to avoid possible memory or computation blowup. + agreement = torch.matmul( + torch.reshape(extra_one_hot, [extra_num_seq, num_res * 23]), + torch.reshape( + sample_one_hot * weights, [num_seq, num_res * 23] + ).transpose(0, 1), + ) + + # Assign each sequence in the extra sequences to the closest MSA sample + protein["extra_cluster_assignment"] = torch.argmax(agreement, dim=1).to( + torch.int64 + ) + + return protein + + +def unsorted_segment_sum(data, segment_ids, num_segments): + """ + Computes the sum along segments of a tensor. Similar to + tf.unsorted_segment_sum, but only supports 1-D indices. + + :param data: A tensor whose segments are to be summed. + :param segment_ids: The 1-D segment indices tensor. + :param num_segments: The number of segments. + :return: A tensor of same data type as the data argument. + """ + assert ( + len(segment_ids.shape) == 1 and + segment_ids.shape[0] == data.shape[0] + ) + segment_ids = segment_ids.view( + segment_ids.shape[0], *((1,) * len(data.shape[1:])) + ) + segment_ids = segment_ids.expand(data.shape) + shape = [num_segments] + list(data.shape[1:]) + tensor = torch.zeros(*shape).scatter_add_(0, segment_ids, data.float()) + tensor = tensor.type(data.dtype) + return tensor + + +@curry1 +def summarize_clusters(protein): + """Produce profile and deletion_matrix_mean within each cluster.""" + num_seq = protein["msa"].shape[0] + + def csum(x): + return unsorted_segment_sum( + x, protein["extra_cluster_assignment"], num_seq + ) + + mask = protein["extra_msa_mask"] + mask_counts = 1e-6 + protein["msa_mask"] + csum(mask) # Include center + + msa_sum = csum(mask[:, :, None] * make_one_hot(protein["extra_msa"], 23)) + msa_sum += make_one_hot(protein["msa"], 23) # Original sequence + protein["cluster_profile"] = msa_sum / mask_counts[:, :, None] + del msa_sum + + del_sum = csum(mask * protein["extra_deletion_matrix"]) + del_sum += protein["deletion_matrix"] # Original sequence + protein["cluster_deletion_mean"] = del_sum / mask_counts + del del_sum + + return protein + + +def make_msa_mask(protein): + """Mask features are all ones, but will later be zero-padded.""" + protein["msa_mask"] = torch.ones(protein["msa"].shape, dtype=torch.float32) + protein["msa_row_mask"] = torch.ones( + (protein["msa"].shape[0]), dtype=torch.float32 + ) + return protein + + +def pseudo_beta_fn(aatype, all_atom_positions, all_atom_mask): + """Create pseudo beta features.""" + is_gly = torch.eq(aatype, rc.restype_order["G"]) + ca_idx = rc.atom_order["CA"] + cb_idx = rc.atom_order["CB"] + pseudo_beta = torch.where( + torch.tile(is_gly[..., None], [1] * len(is_gly.shape) + [3]), + all_atom_positions[..., ca_idx, :], + all_atom_positions[..., cb_idx, :], + ) + + if all_atom_mask is not None: + pseudo_beta_mask = torch.where( + is_gly, all_atom_mask[..., ca_idx], all_atom_mask[..., cb_idx] + ) + return pseudo_beta, pseudo_beta_mask + else: + return pseudo_beta + + +@curry1 +def make_pseudo_beta(protein, prefix=""): + """Create pseudo-beta (alpha for glycine) position and mask.""" + assert prefix in ["", "template_"] + ( + protein[prefix + "pseudo_beta"], + protein[prefix + "pseudo_beta_mask"], + ) = pseudo_beta_fn( + protein["template_aatype" if prefix else "aatype"], + protein[prefix + "all_atom_positions"], + protein["template_all_atom_mask" if prefix else "all_atom_mask"], + ) + return protein + + +@curry1 +def add_constant_field(protein, key, value): + protein[key] = torch.tensor(value) + return protein + + +def shaped_categorical(probs, epsilon=1e-10): + ds = probs.shape + num_classes = ds[-1] + distribution = torch.distributions.categorical.Categorical( + torch.reshape(probs + epsilon, [-1, num_classes]) + ) + counts = distribution.sample() + return torch.reshape(counts, ds[:-1]) + + +def make_hhblits_profile(protein): + """Compute the HHblits MSA profile if not already present.""" + if "hhblits_profile" in protein: + return protein + + # Compute the profile for every residue (over all MSA sequences). + msa_one_hot = make_one_hot(protein["msa"], 22) + + protein["hhblits_profile"] = torch.mean(msa_one_hot, dim=0) + return protein + + +@curry1 +def make_masked_msa(protein, config, replace_fraction): + """Create data for BERT on raw MSA.""" + # Add a random amino acid uniformly. + random_aa = torch.tensor([0.05] * 20 + [0.0, 0.0], dtype=torch.float32) + + categorical_probs = ( + config.uniform_prob * random_aa + + config.profile_prob * protein["hhblits_profile"] + + config.same_prob * make_one_hot(protein["msa"], 22) + ) + + # Put all remaining probability on [MASK] which is a new column + pad_shapes = list( + reduce(add, [(0, 0) for _ in range(len(categorical_probs.shape))]) + ) + pad_shapes[1] = 1 + mask_prob = ( + 1.0 - config.profile_prob - config.same_prob - config.uniform_prob + ) + assert mask_prob >= 0.0 + categorical_probs = torch.nn.functional.pad( + categorical_probs, pad_shapes, value=mask_prob + ) + + sh = protein["msa"].shape + mask_position = torch.rand(sh) < replace_fraction + + bert_msa = shaped_categorical(categorical_probs) + bert_msa = torch.where(mask_position, bert_msa, protein["msa"]) + + # Mix real and masked MSA + protein["bert_mask"] = mask_position.to(torch.float32) + protein["true_msa"] = protein["msa"] + protein["msa"] = bert_msa + + return protein + + +@curry1 +def make_fixed_size( + protein, + shape_schema, + msa_cluster_size, + extra_msa_size, + num_res=0, + num_templates=0, +): + """Guess at the MSA and sequence dimension to make fixed size.""" + pad_size_map = { + NUM_RES: num_res, + NUM_MSA_SEQ: msa_cluster_size, + NUM_EXTRA_SEQ: extra_msa_size, + NUM_TEMPLATES: num_templates, + } + + for k, v in protein.items(): + # Don't transfer this to the accelerator. + if k == "extra_cluster_assignment": + continue + shape = list(v.shape) + schema = shape_schema[k] + msg = "Rank mismatch between shape and shape schema for" + assert len(shape) == len(schema), f"{msg} {k}: {shape} vs {schema}" + pad_size = [ + pad_size_map.get(s2, None) or s1 for (s1, s2) in zip(shape, schema) + ] + + padding = [(0, p - v.shape[i]) for i, p in enumerate(pad_size)] + padding.reverse() + padding = list(itertools.chain(*padding)) + if padding: + protein[k] = torch.nn.functional.pad(v, padding) + protein[k] = torch.reshape(protein[k], pad_size) + + return protein + + +@curry1 +def make_msa_feat(protein): + """Create and concatenate MSA features.""" + # Whether there is a domain break. Always zero for chains, but keeping for + # compatibility with domain datasets. + has_break = torch.clip( + protein["between_segment_residues"].to(torch.float32), 0, 1 + ) + aatype_1hot = make_one_hot(protein["aatype"], 21) + + target_feat = [ + torch.unsqueeze(has_break, dim=-1), + aatype_1hot, # Everyone gets the original sequence. + ] + + msa_1hot = make_one_hot(protein["msa"], 23) + has_deletion = torch.clip(protein["deletion_matrix"], 0.0, 1.0) + deletion_value = torch.atan(protein["deletion_matrix"] / 3.0) * ( + 2.0 / np.pi + ) + + msa_feat = [ + msa_1hot, + torch.unsqueeze(has_deletion, dim=-1), + torch.unsqueeze(deletion_value, dim=-1), + ] + + if "cluster_profile" in protein: + deletion_mean_value = torch.atan( + protein["cluster_deletion_mean"] / 3.0 + ) * (2.0 / np.pi) + msa_feat.extend( + [ + protein["cluster_profile"], + torch.unsqueeze(deletion_mean_value, dim=-1), + ] + ) + + if "extra_deletion_matrix" in protein: + protein["extra_has_deletion"] = torch.clip( + protein["extra_deletion_matrix"], 0.0, 1.0 + ) + protein["extra_deletion_value"] = torch.atan( + protein["extra_deletion_matrix"] / 3.0 + ) * (2.0 / np.pi) + + protein["msa_feat"] = torch.cat(msa_feat, dim=-1) + protein["target_feat"] = torch.cat(target_feat, dim=-1) + return protein + + +@curry1 +def select_feat(protein, feature_list): + return {k: v for k, v in protein.items() if k in feature_list} + + +@curry1 +def crop_templates(protein, max_templates): + for k, v in protein.items(): + if k.startswith("template_"): + protein[k] = v[:max_templates] + return protein + + +def make_atom14_masks(protein): + """Construct denser atom positions (14 dimensions instead of 37).""" + restype_atom14_to_atom37 = [] + restype_atom37_to_atom14 = [] + restype_atom14_mask = [] + + for rt in rc.restypes: + atom_names = rc.restype_name_to_atom14_names[rc.restype_1to3[rt]] + restype_atom14_to_atom37.append( + [(rc.atom_order[name] if name else 0) for name in atom_names] + ) + atom_name_to_idx14 = {name: i for i, name in enumerate(atom_names)} + restype_atom37_to_atom14.append( + [ + (atom_name_to_idx14[name] if name in atom_name_to_idx14 else 0) + for name in rc.atom_types + ] + ) + + restype_atom14_mask.append( + [(1.0 if name else 0.0) for name in atom_names] + ) + + # Add dummy mapping for restype 'UNK' + restype_atom14_to_atom37.append([0] * 14) + restype_atom37_to_atom14.append([0] * 37) + restype_atom14_mask.append([0.0] * 14) + + restype_atom14_to_atom37 = torch.tensor( + restype_atom14_to_atom37, + dtype=torch.int32, + device=protein["aatype"].device, + ) + restype_atom37_to_atom14 = torch.tensor( + restype_atom37_to_atom14, + dtype=torch.int32, + device=protein["aatype"].device, + ) + restype_atom14_mask = torch.tensor( + restype_atom14_mask, + dtype=torch.float32, + device=protein["aatype"].device, + ) + protein_aatype = protein['aatype'].to(torch.long) + + # create the mapping for (residx, atom14) --> atom37, i.e. an array + # with shape (num_res, 14) containing the atom37 indices for this protein + residx_atom14_to_atom37 = restype_atom14_to_atom37[protein_aatype] + residx_atom14_mask = restype_atom14_mask[protein_aatype] + + protein["atom14_atom_exists"] = residx_atom14_mask + protein["residx_atom14_to_atom37"] = residx_atom14_to_atom37.long() + + # create the gather indices for mapping back + residx_atom37_to_atom14 = restype_atom37_to_atom14[protein_aatype] + protein["residx_atom37_to_atom14"] = residx_atom37_to_atom14.long() + + # create the corresponding mask + restype_atom37_mask = torch.zeros( + [21, 37], dtype=torch.float32, device=protein["aatype"].device + ) + for restype, restype_letter in enumerate(rc.restypes): + restype_name = rc.restype_1to3[restype_letter] + atom_names = rc.residue_atoms[restype_name] + for atom_name in atom_names: + atom_type = rc.atom_order[atom_name] + restype_atom37_mask[restype, atom_type] = 1 + + residx_atom37_mask = restype_atom37_mask[protein_aatype] + protein["atom37_atom_exists"] = residx_atom37_mask + + return protein + + +def make_atom14_masks_np(batch): + batch = tree_map(lambda n: torch.tensor(n), batch, np.ndarray) + out = make_atom14_masks(batch) + out = tensor_tree_map(lambda t: np.array(t), out) + return out + + +def make_atom14_positions(protein): + """Constructs denser atom positions (14 dimensions instead of 37).""" + residx_atom14_mask = protein["atom14_atom_exists"] + residx_atom14_to_atom37 = protein["residx_atom14_to_atom37"] + + # Create a mask for known ground truth positions. + residx_atom14_gt_mask = residx_atom14_mask * batched_gather( + protein["all_atom_mask"], + residx_atom14_to_atom37, + dim=-1, + no_batch_dims=len(protein["all_atom_mask"].shape[:-1]), + ) + + # Gather the ground truth positions. + residx_atom14_gt_positions = residx_atom14_gt_mask[..., None] * ( + batched_gather( + protein["all_atom_positions"], + residx_atom14_to_atom37, + dim=-2, + no_batch_dims=len(protein["all_atom_positions"].shape[:-2]), + ) + ) + + protein["atom14_atom_exists"] = residx_atom14_mask + protein["atom14_gt_exists"] = residx_atom14_gt_mask + protein["atom14_gt_positions"] = residx_atom14_gt_positions + + # As the atom naming is ambiguous for 7 of the 20 amino acids, provide + # alternative ground truth coordinates where the naming is swapped + restype_3 = [rc.restype_1to3[res] for res in rc.restypes] + restype_3 += ["UNK"] + + # Matrices for renaming ambiguous atoms. + all_matrices = { + res: torch.eye( + 14, + dtype=protein["all_atom_mask"].dtype, + device=protein["all_atom_mask"].device, + ) + for res in restype_3 + } + for resname, swap in rc.residue_atom_renaming_swaps.items(): + correspondences = torch.arange( + 14, device=protein["all_atom_mask"].device + ) + for source_atom_swap, target_atom_swap in swap.items(): + source_index = rc.restype_name_to_atom14_names[resname].index( + source_atom_swap + ) + target_index = rc.restype_name_to_atom14_names[resname].index( + target_atom_swap + ) + correspondences[source_index] = target_index + correspondences[target_index] = source_index + renaming_matrix = protein["all_atom_mask"].new_zeros((14, 14)) + for index, correspondence in enumerate(correspondences): + renaming_matrix[index, correspondence] = 1.0 + all_matrices[resname] = renaming_matrix + renaming_matrices = torch.stack( + [all_matrices[restype] for restype in restype_3] + ) + + # Pick the transformation matrices for the given residue sequence + # shape (num_res, 14, 14). + renaming_transform = renaming_matrices[protein["aatype"]] + + # Apply it to the ground truth positions. shape (num_res, 14, 3). + alternative_gt_positions = torch.einsum( + "...rac,...rab->...rbc", residx_atom14_gt_positions, renaming_transform + ) + protein["atom14_alt_gt_positions"] = alternative_gt_positions + + # Create the mask for the alternative ground truth (differs from the + # ground truth mask, if only one of the atoms in an ambiguous pair has a + # ground truth position). + alternative_gt_mask = torch.einsum( + "...ra,...rab->...rb", residx_atom14_gt_mask, renaming_transform + ) + protein["atom14_alt_gt_exists"] = alternative_gt_mask + + # Create an ambiguous atoms mask. shape: (21, 14). + restype_atom14_is_ambiguous = protein["all_atom_mask"].new_zeros((21, 14)) + for resname, swap in rc.residue_atom_renaming_swaps.items(): + for atom_name1, atom_name2 in swap.items(): + restype = rc.restype_order[rc.restype_3to1[resname]] + atom_idx1 = rc.restype_name_to_atom14_names[resname].index( + atom_name1 + ) + atom_idx2 = rc.restype_name_to_atom14_names[resname].index( + atom_name2 + ) + restype_atom14_is_ambiguous[restype, atom_idx1] = 1 + restype_atom14_is_ambiguous[restype, atom_idx2] = 1 + + # From this create an ambiguous_mask for the given sequence. + protein["atom14_atom_is_ambiguous"] = restype_atom14_is_ambiguous[ + protein["aatype"] + ] + + return protein + + +def atom37_to_frames(protein, eps=1e-8): + aatype = protein["aatype"] + all_atom_positions = protein["all_atom_positions"] + all_atom_mask = protein["all_atom_mask"] + + batch_dims = len(aatype.shape[:-1]) + + restype_rigidgroup_base_atom_names = np.full([21, 8, 3], "", dtype=object) + restype_rigidgroup_base_atom_names[:, 0, :] = ["C", "CA", "N"] + restype_rigidgroup_base_atom_names[:, 3, :] = ["CA", "C", "O"] + + for restype, restype_letter in enumerate(rc.restypes): + resname = rc.restype_1to3[restype_letter] + for chi_idx in range(4): + if rc.chi_angles_mask[restype][chi_idx]: + names = rc.chi_angles_atoms[resname][chi_idx] + restype_rigidgroup_base_atom_names[ + restype, chi_idx + 4, : + ] = names[1:] + + restype_rigidgroup_mask = all_atom_mask.new_zeros( + (*aatype.shape[:-1], 21, 8), + ) + restype_rigidgroup_mask[..., 0] = 1 + restype_rigidgroup_mask[..., 3] = 1 + restype_rigidgroup_mask[..., :20, 4:] = all_atom_mask.new_tensor( + rc.chi_angles_mask + ) + + lookuptable = rc.atom_order.copy() + lookuptable[""] = 0 + lookup = np.vectorize(lambda x: lookuptable[x]) + restype_rigidgroup_base_atom37_idx = lookup( + restype_rigidgroup_base_atom_names, + ) + restype_rigidgroup_base_atom37_idx = aatype.new_tensor( + restype_rigidgroup_base_atom37_idx, + ) + restype_rigidgroup_base_atom37_idx = ( + restype_rigidgroup_base_atom37_idx.view( + *((1,) * batch_dims), *restype_rigidgroup_base_atom37_idx.shape + ) + ) + + residx_rigidgroup_base_atom37_idx = batched_gather( + restype_rigidgroup_base_atom37_idx, + aatype, + dim=-3, + no_batch_dims=batch_dims, + ) + + base_atom_pos = batched_gather( + all_atom_positions, + residx_rigidgroup_base_atom37_idx, + dim=-2, + no_batch_dims=len(all_atom_positions.shape[:-2]), + ) + + gt_frames = Rigid.from_3_points( + p_neg_x_axis=base_atom_pos[..., 0, :], + origin=base_atom_pos[..., 1, :], + p_xy_plane=base_atom_pos[..., 2, :], + eps=eps, + ) + + group_exists = batched_gather( + restype_rigidgroup_mask, + aatype, + dim=-2, + no_batch_dims=batch_dims, + ) + + gt_atoms_exist = batched_gather( + all_atom_mask, + residx_rigidgroup_base_atom37_idx, + dim=-1, + no_batch_dims=len(all_atom_mask.shape[:-1]), + ) + gt_exists = torch.min(gt_atoms_exist, dim=-1)[0] * group_exists + + rots = torch.eye(3, dtype=all_atom_mask.dtype, device=aatype.device) + rots = torch.tile(rots, (*((1,) * batch_dims), 8, 1, 1)) + rots[..., 0, 0, 0] = -1 + rots[..., 0, 2, 2] = -1 + rots = Rotation(rot_mats=rots) + + gt_frames = gt_frames.compose(Rigid(rots, None)) + + restype_rigidgroup_is_ambiguous = all_atom_mask.new_zeros( + *((1,) * batch_dims), 21, 8 + ) + restype_rigidgroup_rots = torch.eye( + 3, dtype=all_atom_mask.dtype, device=aatype.device + ) + restype_rigidgroup_rots = torch.tile( + restype_rigidgroup_rots, + (*((1,) * batch_dims), 21, 8, 1, 1), + ) + + for resname, _ in rc.residue_atom_renaming_swaps.items(): + restype = rc.restype_order[rc.restype_3to1[resname]] + chi_idx = int(sum(rc.chi_angles_mask[restype]) - 1) + restype_rigidgroup_is_ambiguous[..., restype, chi_idx + 4] = 1 + restype_rigidgroup_rots[..., restype, chi_idx + 4, 1, 1] = -1 + restype_rigidgroup_rots[..., restype, chi_idx + 4, 2, 2] = -1 + + residx_rigidgroup_is_ambiguous = batched_gather( + restype_rigidgroup_is_ambiguous, + aatype, + dim=-2, + no_batch_dims=batch_dims, + ) + + residx_rigidgroup_ambiguity_rot = batched_gather( + restype_rigidgroup_rots, + aatype, + dim=-4, + no_batch_dims=batch_dims, + ) + + residx_rigidgroup_ambiguity_rot = Rotation( + rot_mats=residx_rigidgroup_ambiguity_rot + ) + alt_gt_frames = gt_frames.compose( + Rigid(residx_rigidgroup_ambiguity_rot, None) + ) + + gt_frames_tensor = gt_frames.to_tensor_4x4() + alt_gt_frames_tensor = alt_gt_frames.to_tensor_4x4() + + protein["rigidgroups_gt_frames"] = gt_frames_tensor + protein["rigidgroups_gt_exists"] = gt_exists + protein["rigidgroups_group_exists"] = group_exists + protein["rigidgroups_group_is_ambiguous"] = residx_rigidgroup_is_ambiguous + protein["rigidgroups_alt_gt_frames"] = alt_gt_frames_tensor + + return protein + + +def get_chi_atom_indices(): + """Returns atom indices needed to compute chi angles for all residue types. + + Returns: + A tensor of shape [residue_types=21, chis=4, atoms=4]. The residue types are + in the order specified in rc.restypes + unknown residue type + at the end. For chi angles which are not defined on the residue, the + positions indices are by default set to 0. + """ + chi_atom_indices = [] + for residue_name in rc.restypes: + residue_name = rc.restype_1to3[residue_name] + residue_chi_angles = rc.chi_angles_atoms[residue_name] + atom_indices = [] + for chi_angle in residue_chi_angles: + atom_indices.append([rc.atom_order[atom] for atom in chi_angle]) + for _ in range(4 - len(atom_indices)): + atom_indices.append( + [0, 0, 0, 0] + ) # For chi angles not defined on the AA. + chi_atom_indices.append(atom_indices) + + chi_atom_indices.append([[0, 0, 0, 0]] * 4) # For UNKNOWN residue. + + return chi_atom_indices + + +@curry1 +def atom37_to_torsion_angles( + protein, + prefix="", +): + """ + Convert coordinates to torsion angles. + + This function is extremely sensitive to floating point imprecisions + and should be run with double precision whenever possible. + + Args: + Dict containing: + * (prefix)aatype: + [*, N_res] residue indices + * (prefix)all_atom_positions: + [*, N_res, 37, 3] atom positions (in atom37 + format) + * (prefix)all_atom_mask: + [*, N_res, 37] atom position mask + Returns: + The same dictionary updated with the following features: + + "(prefix)torsion_angles_sin_cos" ([*, N_res, 7, 2]) + Torsion angles + "(prefix)alt_torsion_angles_sin_cos" ([*, N_res, 7, 2]) + Alternate torsion angles (accounting for 180-degree symmetry) + "(prefix)torsion_angles_mask" ([*, N_res, 7]) + Torsion angles mask + """ + aatype = protein[prefix + "aatype"] + all_atom_positions = protein[prefix + "all_atom_positions"] + all_atom_mask = protein[prefix + "all_atom_mask"] + + aatype = torch.clamp(aatype, max=20) + + pad = all_atom_positions.new_zeros( + [*all_atom_positions.shape[:-3], 1, 37, 3] + ) + prev_all_atom_positions = torch.cat( + [pad, all_atom_positions[..., :-1, :, :]], dim=-3 + ) + + pad = all_atom_mask.new_zeros([*all_atom_mask.shape[:-2], 1, 37]) + prev_all_atom_mask = torch.cat([pad, all_atom_mask[..., :-1, :]], dim=-2) + + pre_omega_atom_pos = torch.cat( + [prev_all_atom_positions[..., 1:3, :], all_atom_positions[..., :2, :]], + dim=-2, + ) + phi_atom_pos = torch.cat( + [prev_all_atom_positions[..., 2:3, :], all_atom_positions[..., :3, :]], + dim=-2, + ) + psi_atom_pos = torch.cat( + [all_atom_positions[..., :3, :], all_atom_positions[..., 4:5, :]], + dim=-2, + ) + + pre_omega_mask = torch.prod( + prev_all_atom_mask[..., 1:3], dim=-1 + ) * torch.prod(all_atom_mask[..., :2], dim=-1) + phi_mask = prev_all_atom_mask[..., 2] * torch.prod( + all_atom_mask[..., :3], dim=-1, dtype=all_atom_mask.dtype + ) + psi_mask = ( + torch.prod(all_atom_mask[..., :3], dim=-1, dtype=all_atom_mask.dtype) + * all_atom_mask[..., 4] + ) + + chi_atom_indices = torch.as_tensor( + get_chi_atom_indices(), device=aatype.device + ) + + atom_indices = chi_atom_indices[..., aatype, :, :] + chis_atom_pos = batched_gather( + all_atom_positions, atom_indices, -2, len(atom_indices.shape[:-2]) + ) + + chi_angles_mask = list(rc.chi_angles_mask) + chi_angles_mask.append([0.0, 0.0, 0.0, 0.0]) + chi_angles_mask = all_atom_mask.new_tensor(chi_angles_mask) + + chis_mask = chi_angles_mask[aatype, :] + + chi_angle_atoms_mask = batched_gather( + all_atom_mask, + atom_indices, + dim=-1, + no_batch_dims=len(atom_indices.shape[:-2]), + ) + chi_angle_atoms_mask = torch.prod( + chi_angle_atoms_mask, dim=-1, dtype=chi_angle_atoms_mask.dtype + ) + chis_mask = chis_mask * chi_angle_atoms_mask + + torsions_atom_pos = torch.cat( + [ + pre_omega_atom_pos[..., None, :, :], + phi_atom_pos[..., None, :, :], + psi_atom_pos[..., None, :, :], + chis_atom_pos, + ], + dim=-3, + ) + + torsion_angles_mask = torch.cat( + [ + pre_omega_mask[..., None], + phi_mask[..., None], + psi_mask[..., None], + chis_mask, + ], + dim=-1, + ) + + torsion_frames = Rigid.from_3_points( + torsions_atom_pos[..., 1, :], + torsions_atom_pos[..., 2, :], + torsions_atom_pos[..., 0, :], + eps=1e-8, + ) + + fourth_atom_rel_pos = torsion_frames.invert().apply( + torsions_atom_pos[..., 3, :] + ) + + torsion_angles_sin_cos = torch.stack( + [fourth_atom_rel_pos[..., 2], fourth_atom_rel_pos[..., 1]], dim=-1 + ) + + denom = torch.sqrt( + torch.sum( + torch.square(torsion_angles_sin_cos), + dim=-1, + dtype=torsion_angles_sin_cos.dtype, + keepdims=True, + ) + + 1e-8 + ) + torsion_angles_sin_cos = torsion_angles_sin_cos / denom + + torsion_angles_sin_cos = torsion_angles_sin_cos * all_atom_mask.new_tensor( + [1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0], + )[((None,) * len(torsion_angles_sin_cos.shape[:-2])) + (slice(None), None)] + + chi_is_ambiguous = torsion_angles_sin_cos.new_tensor( + rc.chi_pi_periodic, + )[aatype, ...] + + mirror_torsion_angles = torch.cat( + [ + all_atom_mask.new_ones(*aatype.shape, 3), + 1.0 - 2.0 * chi_is_ambiguous, + ], + dim=-1, + ) + + alt_torsion_angles_sin_cos = ( + torsion_angles_sin_cos * mirror_torsion_angles[..., None] + ) + + protein[prefix + "torsion_angles_sin_cos"] = torsion_angles_sin_cos + protein[prefix + "alt_torsion_angles_sin_cos"] = alt_torsion_angles_sin_cos + protein[prefix + "torsion_angles_mask"] = torsion_angles_mask + + return protein + + +def get_backbone_frames(protein): + # DISCREPANCY: AlphaFold uses tensor_7s here. I don't know why. + protein["backbone_rigid_tensor"] = protein["rigidgroups_gt_frames"][ + ..., 0, :, : + ] + protein["backbone_rigid_mask"] = protein["rigidgroups_gt_exists"][..., 0] + + return protein + + +def get_chi_angles(protein): + dtype = protein["all_atom_mask"].dtype + protein["chi_angles_sin_cos"] = ( + protein["torsion_angles_sin_cos"][..., 3:, :] + ).to(dtype) + protein["chi_mask"] = protein["torsion_angles_mask"][..., 3:].to(dtype) + + return protein + + +@curry1 +def random_crop_to_size( + protein, + crop_size, + max_templates, + shape_schema, + subsample_templates=False, + seed=None, +): + """Crop randomly to `crop_size`, or keep as is if shorter than that.""" + # We want each ensemble to be cropped the same way + g = torch.Generator(device=protein["seq_length"].device) + if seed is not None: + g.manual_seed(seed) + + seq_length = protein["seq_length"] + + if "template_mask" in protein: + num_templates = protein["template_mask"].shape[-1] + else: + num_templates = 0 + + # No need to subsample templates if there aren't any + subsample_templates = subsample_templates and num_templates + + num_res_crop_size = min(int(seq_length), crop_size) + + def _randint(lower, upper): + return int(torch.randint( + lower, + upper + 1, + (1,), + device=protein["seq_length"].device, + generator=g, + )[0]) + + if subsample_templates: + templates_crop_start = _randint(0, num_templates) + templates_select_indices = torch.randperm( + num_templates, device=protein["seq_length"].device, generator=g + ) + else: + templates_crop_start = 0 + + num_templates_crop_size = min( + num_templates - templates_crop_start, max_templates + ) + + n = seq_length - num_res_crop_size + if "use_clamped_fape" in protein and protein["use_clamped_fape"] == 1.: + right_anchor = n + else: + x = _randint(0, n) + right_anchor = n - x + + num_res_crop_start = _randint(0, right_anchor) + + for k, v in protein.items(): + if k not in shape_schema or ( + "template" not in k and NUM_RES not in shape_schema[k] + ): + continue + + # randomly permute the templates before cropping them. + if k.startswith("template") and subsample_templates: + v = v[templates_select_indices] + + slices = [] + for i, (dim_size, dim) in enumerate(zip(shape_schema[k], v.shape)): + is_num_res = dim_size == NUM_RES + if i == 0 and k.startswith("template"): + crop_size = num_templates_crop_size + crop_start = templates_crop_start + else: + crop_start = num_res_crop_start if is_num_res else 0 + crop_size = num_res_crop_size if is_num_res else dim + slices.append(slice(crop_start, crop_start + crop_size)) + protein[k] = v[slices] + + protein["seq_length"] = protein["seq_length"].new_tensor(num_res_crop_size) + + return protein diff --git a/gafl/openfold/data/errors.py b/gafl/openfold/data/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..7809d5ae29a736ccc7688d555a06a5301a3ab46f --- /dev/null +++ b/gafl/openfold/data/errors.py @@ -0,0 +1,22 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""General-purpose errors used throughout the data pipeline""" +class Error(Exception): + """Base class for exceptions.""" + + +class MultipleChainsError(Error): + """An error indicating that multiple chains were found for a given ID.""" diff --git a/gafl/openfold/data/feature_pipeline.py b/gafl/openfold/data/feature_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..77b9a9f2570d01307b724ca73cf3b00016526383 --- /dev/null +++ b/gafl/openfold/data/feature_pipeline.py @@ -0,0 +1,115 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from typing import Mapping, Tuple, List, Optional, Dict, Sequence + +import ml_collections +import numpy as np +import torch + +from openfold.data import input_pipeline + + +FeatureDict = Mapping[str, np.ndarray] +TensorDict = Dict[str, torch.Tensor] + + +def np_to_tensor_dict( + np_example: Mapping[str, np.ndarray], + features: Sequence[str], +) -> TensorDict: + """Creates dict of tensors from a dict of NumPy arrays. + + Args: + np_example: A dict of NumPy feature arrays. + features: A list of strings of feature names to be returned in the dataset. + + Returns: + A dictionary of features mapping feature names to features. Only the given + features are returned, all other ones are filtered out. + """ + tensor_dict = { + k: torch.tensor(v) for k, v in np_example.items() if k in features + } + return tensor_dict + + +def make_data_config( + config: ml_collections.ConfigDict, + mode: str, + num_res: int, +) -> Tuple[ml_collections.ConfigDict, List[str]]: + cfg = copy.deepcopy(config) + mode_cfg = cfg[mode] + with cfg.unlocked(): + if mode_cfg.crop_size is None: + mode_cfg.crop_size = num_res + + feature_names = cfg.common.unsupervised_features + + if cfg.common.use_templates: + feature_names += cfg.common.template_features + + if cfg[mode].supervised: + feature_names += cfg.supervised.supervised_features + + return cfg, feature_names + + +def np_example_to_features( + np_example: FeatureDict, + config: ml_collections.ConfigDict, + mode: str, +): + np_example = dict(np_example) + num_res = int(np_example["seq_length"][0]) + cfg, feature_names = make_data_config(config, mode=mode, num_res=num_res) + + if "deletion_matrix_int" in np_example: + np_example["deletion_matrix"] = np_example.pop( + "deletion_matrix_int" + ).astype(np.float32) + + tensor_dict = np_to_tensor_dict( + np_example=np_example, features=feature_names + ) + with torch.no_grad(): + features = input_pipeline.process_tensors_from_config( + tensor_dict, + cfg.common, + cfg[mode], + ) + + return {k: v for k, v in features.items()} + + +class FeaturePipeline: + def __init__( + self, + config: ml_collections.ConfigDict, + ): + self.config = config + + def process_features( + self, + raw_features: FeatureDict, + mode: str = "train", + ) -> FeatureDict: + return np_example_to_features( + np_example=raw_features, + config=self.config, + mode=mode, + ) diff --git a/gafl/openfold/data/input_pipeline.py b/gafl/openfold/data/input_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..b706ec3df523580d25d1603fc7f653c597be2902 --- /dev/null +++ b/gafl/openfold/data/input_pipeline.py @@ -0,0 +1,208 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial + +import torch + +from openfold.data import data_transforms + + +def nonensembled_transform_fns(common_cfg, mode_cfg): + """Input pipeline data transformers that are not ensembled.""" + transforms = [ + data_transforms.cast_to_64bit_ints, + data_transforms.correct_msa_restypes, + data_transforms.squeeze_features, + data_transforms.randomly_replace_msa_with_unknown(0.0), + data_transforms.make_seq_mask, + data_transforms.make_msa_mask, + data_transforms.make_hhblits_profile, + ] + if common_cfg.use_templates: + transforms.extend( + [ + data_transforms.fix_templates_aatype, + data_transforms.make_template_mask, + data_transforms.make_pseudo_beta("template_"), + ] + ) + if common_cfg.use_template_torsion_angles: + transforms.extend( + [ + data_transforms.atom37_to_torsion_angles("template_"), + ] + ) + + transforms.extend( + [ + data_transforms.make_atom14_masks, + ] + ) + + if mode_cfg.supervised: + transforms.extend( + [ + data_transforms.make_atom14_positions, + data_transforms.atom37_to_frames, + data_transforms.atom37_to_torsion_angles(""), + data_transforms.make_pseudo_beta(""), + data_transforms.get_backbone_frames, + data_transforms.get_chi_angles, + ] + ) + + return transforms + + +def ensembled_transform_fns(common_cfg, mode_cfg, ensemble_seed): + """Input pipeline data transformers that can be ensembled and averaged.""" + transforms = [] + + if "max_distillation_msa_clusters" in mode_cfg: + transforms.append( + data_transforms.sample_msa_distillation( + mode_cfg.max_distillation_msa_clusters + ) + ) + + if common_cfg.reduce_msa_clusters_by_max_templates: + pad_msa_clusters = mode_cfg.max_msa_clusters - mode_cfg.max_templates + else: + pad_msa_clusters = mode_cfg.max_msa_clusters + + max_msa_clusters = pad_msa_clusters + max_extra_msa = common_cfg.max_extra_msa + + msa_seed = None + if(not common_cfg.resample_msa_in_recycling): + msa_seed = ensemble_seed + + transforms.append( + data_transforms.sample_msa( + max_msa_clusters, + keep_extra=True, + seed=msa_seed, + ) + ) + + if "masked_msa" in common_cfg: + # Masked MSA should come *before* MSA clustering so that + # the clustering and full MSA profile do not leak information about + # the masked locations and secret corrupted locations. + transforms.append( + data_transforms.make_masked_msa( + common_cfg.masked_msa, mode_cfg.masked_msa_replace_fraction + ) + ) + + if common_cfg.msa_cluster_features: + transforms.append(data_transforms.nearest_neighbor_clusters()) + transforms.append(data_transforms.summarize_clusters()) + + # Crop after creating the cluster profiles. + if max_extra_msa: + transforms.append(data_transforms.crop_extra_msa(max_extra_msa)) + else: + transforms.append(data_transforms.delete_extra_msa) + + transforms.append(data_transforms.make_msa_feat()) + + crop_feats = dict(common_cfg.feat) + + if mode_cfg.fixed_size: + transforms.append(data_transforms.select_feat(list(crop_feats))) + transforms.append( + data_transforms.random_crop_to_size( + mode_cfg.crop_size, + mode_cfg.max_templates, + crop_feats, + mode_cfg.subsample_templates, + seed=ensemble_seed + 1, + ) + ) + transforms.append( + data_transforms.make_fixed_size( + crop_feats, + pad_msa_clusters, + common_cfg.max_extra_msa, + mode_cfg.crop_size, + mode_cfg.max_templates, + ) + ) + else: + transforms.append( + data_transforms.crop_templates(mode_cfg.max_templates) + ) + + return transforms + + +def process_tensors_from_config(tensors, common_cfg, mode_cfg): + """Based on the config, apply filters and transformations to the data.""" + + ensemble_seed = torch.Generator().seed() + + def wrap_ensemble_fn(data, i): + """Function to be mapped over the ensemble dimension.""" + d = data.copy() + fns = ensembled_transform_fns( + common_cfg, + mode_cfg, + ensemble_seed, + ) + fn = compose(fns) + d["ensemble_index"] = i + return fn(d) + + no_templates = True + if("template_aatype" in tensors): + no_templates = tensors["template_aatype"].shape[0] == 0 + + nonensembled = nonensembled_transform_fns( + common_cfg, + mode_cfg, + ) + + tensors = compose(nonensembled)(tensors) + + if("no_recycling_iters" in tensors): + num_recycling = int(tensors["no_recycling_iters"]) + else: + num_recycling = common_cfg.max_recycling_iters + + tensors = map_fn( + lambda x: wrap_ensemble_fn(tensors, x), torch.arange(num_recycling + 1) + ) + + return tensors + + +@data_transforms.curry1 +def compose(x, fs): + for f in fs: + x = f(x) + return x + + +def map_fn(fun, x): + ensembles = [fun(elem) for elem in x] + features = ensembles[0].keys() + ensembled_dict = {} + for feat in features: + ensembled_dict[feat] = torch.stack( + [dict_i[feat] for dict_i in ensembles], dim=-1 + ) + return ensembled_dict diff --git a/gafl/openfold/data/mmcif_parsing.py b/gafl/openfold/data/mmcif_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..c95047e1f9ab0cf1549b51d9f01da1c5e26080f1 --- /dev/null +++ b/gafl/openfold/data/mmcif_parsing.py @@ -0,0 +1,485 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Parses the mmCIF file format.""" +import collections +import dataclasses +import io +import json +import logging +import os +from typing import Any, Mapping, Optional, Sequence, Tuple + +from Bio import PDB +from Bio.Data import SCOPData +import numpy as np + +from openfold.data.errors import MultipleChainsError +import openfold.np.residue_constants as residue_constants + + +# Type aliases: +ChainId = str +PdbHeader = Mapping[str, Any] +PdbStructure = PDB.Structure.Structure +SeqRes = str +MmCIFDict = Mapping[str, Sequence[str]] + + +@dataclasses.dataclass(frozen=True) +class Monomer: + id: str + num: int + + +# Note - mmCIF format provides no guarantees on the type of author-assigned +# sequence numbers. They need not be integers. +@dataclasses.dataclass(frozen=True) +class AtomSite: + residue_name: str + author_chain_id: str + mmcif_chain_id: str + author_seq_num: str + mmcif_seq_num: int + insertion_code: str + hetatm_atom: str + model_num: int + + +# Used to map SEQRES index to a residue in the structure. +@dataclasses.dataclass(frozen=True) +class ResiduePosition: + chain_id: str + residue_number: int + insertion_code: str + + +@dataclasses.dataclass(frozen=True) +class ResidueAtPosition: + position: Optional[ResiduePosition] + name: str + is_missing: bool + hetflag: str + + +@dataclasses.dataclass(frozen=True) +class MmcifObject: + """Representation of a parsed mmCIF file. + + Contains: + file_id: A meaningful name, e.g. a pdb_id. Should be unique amongst all + files being processed. + header: Biopython header. + structure: Biopython structure. + chain_to_seqres: Dict mapping chain_id to 1 letter amino acid sequence. E.g. + {'A': 'ABCDEFG'} + seqres_to_structure: Dict; for each chain_id contains a mapping between + SEQRES index and a ResidueAtPosition. e.g. {'A': {0: ResidueAtPosition, + 1: ResidueAtPosition, + ...}} + raw_string: The raw string used to construct the MmcifObject. + """ + + file_id: str + header: PdbHeader + structure: PdbStructure + chain_to_seqres: Mapping[ChainId, SeqRes] + seqres_to_structure: Mapping[ChainId, Mapping[int, ResidueAtPosition]] + raw_string: Any + + +@dataclasses.dataclass(frozen=True) +class ParsingResult: + """Returned by the parse function. + + Contains: + mmcif_object: A MmcifObject, may be None if no chain could be successfully + parsed. + errors: A dict mapping (file_id, chain_id) to any exception generated. + """ + + mmcif_object: Optional[MmcifObject] + errors: Mapping[Tuple[str, str], Any] + + +class ParseError(Exception): + """An error indicating that an mmCIF file could not be parsed.""" + + +def mmcif_loop_to_list( + prefix: str, parsed_info: MmCIFDict +) -> Sequence[Mapping[str, str]]: + """Extracts loop associated with a prefix from mmCIF data as a list. + + Reference for loop_ in mmCIF: + http://mmcif.wwpdb.org/docs/tutorials/mechanics/pdbx-mmcif-syntax.html + + Args: + prefix: Prefix shared by each of the data items in the loop. + e.g. '_entity_poly_seq.', where the data items are _entity_poly_seq.num, + _entity_poly_seq.mon_id. Should include the trailing period. + parsed_info: A dict of parsed mmCIF data, e.g. _mmcif_dict from a Biopython + parser. + + Returns: + Returns a list of dicts; each dict represents 1 entry from an mmCIF loop. + """ + cols = [] + data = [] + for key, value in parsed_info.items(): + if key.startswith(prefix): + cols.append(key) + data.append(value) + + assert all([len(xs) == len(data[0]) for xs in data]), ( + "mmCIF error: Not all loops are the same length: %s" % cols + ) + + return [dict(zip(cols, xs)) for xs in zip(*data)] + + +def mmcif_loop_to_dict( + prefix: str, + index: str, + parsed_info: MmCIFDict, +) -> Mapping[str, Mapping[str, str]]: + """Extracts loop associated with a prefix from mmCIF data as a dictionary. + + Args: + prefix: Prefix shared by each of the data items in the loop. + e.g. '_entity_poly_seq.', where the data items are _entity_poly_seq.num, + _entity_poly_seq.mon_id. Should include the trailing period. + index: Which item of loop data should serve as the key. + parsed_info: A dict of parsed mmCIF data, e.g. _mmcif_dict from a Biopython + parser. + + Returns: + Returns a dict of dicts; each dict represents 1 entry from an mmCIF loop, + indexed by the index column. + """ + entries = mmcif_loop_to_list(prefix, parsed_info) + return {entry[index]: entry for entry in entries} + + +def parse( + *, file_id: str, mmcif_string: str, catch_all_errors: bool = True +) -> ParsingResult: + """Entry point, parses an mmcif_string. + + Args: + file_id: A string identifier for this file. Should be unique within the + collection of files being processed. + mmcif_string: Contents of an mmCIF file. + catch_all_errors: If True, all exceptions are caught and error messages are + returned as part of the ParsingResult. If False exceptions will be allowed + to propagate. + + Returns: + A ParsingResult. + """ + errors = {} + try: + parser = PDB.MMCIFParser(QUIET=True) + handle = io.StringIO(mmcif_string) + full_structure = parser.get_structure("", handle) + first_model_structure = _get_first_model(full_structure) + # Extract the _mmcif_dict from the parser, which contains useful fields not + # reflected in the Biopython structure. + parsed_info = parser._mmcif_dict # pylint:disable=protected-access + + # Ensure all values are lists, even if singletons. + for key, value in parsed_info.items(): + if not isinstance(value, list): + parsed_info[key] = [value] + + header = _get_header(parsed_info) + + # Determine the protein chains, and their start numbers according to the + # internal mmCIF numbering scheme (likely but not guaranteed to be 1). + valid_chains = _get_protein_chains(parsed_info=parsed_info) + if not valid_chains: + return ParsingResult( + None, {(file_id, ""): "No protein chains found in this file."} + ) + seq_start_num = { + chain_id: min([monomer.num for monomer in seq]) + for chain_id, seq in valid_chains.items() + } + + # Loop over the atoms for which we have coordinates. Populate two mappings: + # -mmcif_to_author_chain_id (maps internal mmCIF chain ids to chain ids used + # the authors / Biopython). + # -seq_to_structure_mappings (maps idx into sequence to ResidueAtPosition). + mmcif_to_author_chain_id = {} + seq_to_structure_mappings = {} + for atom in _get_atom_site_list(parsed_info): + if atom.model_num != "1": + # We only process the first model at the moment. + continue + + mmcif_to_author_chain_id[atom.mmcif_chain_id] = atom.author_chain_id + + if atom.mmcif_chain_id in valid_chains: + hetflag = " " + if atom.hetatm_atom == "HETATM": + # Water atoms are assigned a special hetflag of W in Biopython. We + # need to do the same, so that this hetflag can be used to fetch + # a residue from the Biopython structure by id. + if atom.residue_name in ("HOH", "WAT"): + hetflag = "W" + else: + hetflag = "H_" + atom.residue_name + insertion_code = atom.insertion_code + if not _is_set(atom.insertion_code): + insertion_code = " " + position = ResiduePosition( + chain_id=atom.author_chain_id, + residue_number=int(atom.author_seq_num), + insertion_code=insertion_code, + ) + seq_idx = ( + int(atom.mmcif_seq_num) - seq_start_num[atom.mmcif_chain_id] + ) + current = seq_to_structure_mappings.get( + atom.author_chain_id, {} + ) + current[seq_idx] = ResidueAtPosition( + position=position, + name=atom.residue_name, + is_missing=False, + hetflag=hetflag, + ) + seq_to_structure_mappings[atom.author_chain_id] = current + + # Add missing residue information to seq_to_structure_mappings. + for chain_id, seq_info in valid_chains.items(): + author_chain = mmcif_to_author_chain_id[chain_id] + current_mapping = seq_to_structure_mappings[author_chain] + for idx, monomer in enumerate(seq_info): + if idx not in current_mapping: + current_mapping[idx] = ResidueAtPosition( + position=None, + name=monomer.id, + is_missing=True, + hetflag=" ", + ) + + author_chain_to_sequence = {} + for chain_id, seq_info in valid_chains.items(): + author_chain = mmcif_to_author_chain_id[chain_id] + seq = [] + for monomer in seq_info: + code = SCOPData.protein_letters_3to1.get(monomer.id, "X") + seq.append(code if len(code) == 1 else "X") + seq = "".join(seq) + author_chain_to_sequence[author_chain] = seq + + mmcif_object = MmcifObject( + file_id=file_id, + header=header, + structure=first_model_structure, + chain_to_seqres=author_chain_to_sequence, + seqres_to_structure=seq_to_structure_mappings, + raw_string=parsed_info, + ) + + return ParsingResult(mmcif_object=mmcif_object, errors=errors) + except Exception as e: # pylint:disable=broad-except + errors[(file_id, "")] = e + if not catch_all_errors: + raise + return ParsingResult(mmcif_object=None, errors=errors) + + +def _get_first_model(structure: PdbStructure) -> PdbStructure: + """Returns the first model in a Biopython structure.""" + return next(structure.get_models()) + + +_MIN_LENGTH_OF_CHAIN_TO_BE_COUNTED_AS_PEPTIDE = 21 + + +def get_release_date(parsed_info: MmCIFDict) -> str: + """Returns the oldest revision date.""" + revision_dates = parsed_info["_pdbx_audit_revision_history.revision_date"] + return min(revision_dates) + + +def _get_header(parsed_info: MmCIFDict) -> PdbHeader: + """Returns a basic header containing method, release date and resolution.""" + header = {} + + experiments = mmcif_loop_to_list("_exptl.", parsed_info) + header["structure_method"] = ",".join( + [experiment["_exptl.method"].lower() for experiment in experiments] + ) + + # Note: The release_date here corresponds to the oldest revision. We prefer to + # use this for dataset filtering over the deposition_date. + if "_pdbx_audit_revision_history.revision_date" in parsed_info: + header["release_date"] = get_release_date(parsed_info) + else: + logging.warning( + "Could not determine release_date: %s", parsed_info["_entry.id"] + ) + + header["resolution"] = 0.00 + for res_key in ( + "_refine.ls_d_res_high", + "_em_3d_reconstruction.resolution", + "_reflns.d_resolution_high", + ): + if res_key in parsed_info: + try: + raw_resolution = parsed_info[res_key][0] + header["resolution"] = float(raw_resolution) + except ValueError: + logging.info( + "Invalid resolution format: %s", parsed_info[res_key] + ) + + return header + + +def _get_atom_site_list(parsed_info: MmCIFDict) -> Sequence[AtomSite]: + """Returns list of atom sites; contains data not present in the structure.""" + return [ + AtomSite(*site) + for site in zip( # pylint:disable=g-complex-comprehension + parsed_info["_atom_site.label_comp_id"], + parsed_info["_atom_site.auth_asym_id"], + parsed_info["_atom_site.label_asym_id"], + parsed_info["_atom_site.auth_seq_id"], + parsed_info["_atom_site.label_seq_id"], + parsed_info["_atom_site.pdbx_PDB_ins_code"], + parsed_info["_atom_site.group_PDB"], + parsed_info["_atom_site.pdbx_PDB_model_num"], + ) + ] + + +def _get_protein_chains( + *, parsed_info: Mapping[str, Any] +) -> Mapping[ChainId, Sequence[Monomer]]: + """Extracts polymer information for protein chains only. + + Args: + parsed_info: _mmcif_dict produced by the Biopython parser. + + Returns: + A dict mapping mmcif chain id to a list of Monomers. + """ + # Get polymer information for each entity in the structure. + entity_poly_seqs = mmcif_loop_to_list("_entity_poly_seq.", parsed_info) + + polymers = collections.defaultdict(list) + for entity_poly_seq in entity_poly_seqs: + polymers[entity_poly_seq["_entity_poly_seq.entity_id"]].append( + Monomer( + id=entity_poly_seq["_entity_poly_seq.mon_id"], + num=int(entity_poly_seq["_entity_poly_seq.num"]), + ) + ) + + # Get chemical compositions. Will allow us to identify which of these polymers + # are proteins. + chem_comps = mmcif_loop_to_dict("_chem_comp.", "_chem_comp.id", parsed_info) + + # Get chains information for each entity. Necessary so that we can return a + # dict keyed on chain id rather than entity. + struct_asyms = mmcif_loop_to_list("_struct_asym.", parsed_info) + + entity_to_mmcif_chains = collections.defaultdict(list) + for struct_asym in struct_asyms: + chain_id = struct_asym["_struct_asym.id"] + entity_id = struct_asym["_struct_asym.entity_id"] + entity_to_mmcif_chains[entity_id].append(chain_id) + + # Identify and return the valid protein chains. + valid_chains = {} + for entity_id, seq_info in polymers.items(): + chain_ids = entity_to_mmcif_chains[entity_id] + + # Reject polymers without any peptide-like components, such as DNA/RNA. + if any( + [ + "peptide" in chem_comps[monomer.id]["_chem_comp.type"] + for monomer in seq_info + ] + ): + for chain_id in chain_ids: + valid_chains[chain_id] = seq_info + return valid_chains + + +def _is_set(data: str) -> bool: + """Returns False if data is a special mmCIF character indicating 'unset'.""" + return data not in (".", "?") + + +def get_atom_coords( + mmcif_object: MmcifObject, + chain_id: str, + _zero_center_positions: bool = True +) -> Tuple[np.ndarray, np.ndarray]: + # Locate the right chain + chains = list(mmcif_object.structure.get_chains()) + relevant_chains = [c for c in chains if c.id == chain_id] + if len(relevant_chains) != 1: + raise MultipleChainsError( + f"Expected exactly one chain in structure with id {chain_id}." + ) + chain = relevant_chains[0] + + # Extract the coordinates + num_res = len(mmcif_object.chain_to_seqres[chain_id]) + all_atom_positions = np.zeros( + [num_res, residue_constants.atom_type_num, 3], dtype=np.float32 + ) + all_atom_mask = np.zeros( + [num_res, residue_constants.atom_type_num], dtype=np.float32 + ) + for res_index in range(num_res): + pos = np.zeros([residue_constants.atom_type_num, 3], dtype=np.float32) + mask = np.zeros([residue_constants.atom_type_num], dtype=np.float32) + res_at_position = mmcif_object.seqres_to_structure[chain_id][res_index] + if not res_at_position.is_missing: + res = chain[ + ( + res_at_position.hetflag, + res_at_position.position.residue_number, + res_at_position.position.insertion_code, + ) + ] + for atom in res.get_atoms(): + atom_name = atom.get_name() + x, y, z = atom.get_coord() + if atom_name in residue_constants.atom_order.keys(): + pos[residue_constants.atom_order[atom_name]] = [x, y, z] + mask[residue_constants.atom_order[atom_name]] = 1.0 + elif atom_name.upper() == "SE" and res.get_resname() == "MSE": + # Put the coords of the selenium atom in the sulphur column + pos[residue_constants.atom_order["SD"]] = [x, y, z] + mask[residue_constants.atom_order["SD"]] = 1.0 + + all_atom_positions[res_index] = pos + all_atom_mask[res_index] = mask + + if _zero_center_positions: + binary_mask = all_atom_mask.astype(bool) + translation_vec = all_atom_positions[binary_mask].mean(axis=0) + all_atom_positions[binary_mask] -= translation_vec + + return all_atom_positions, all_atom_mask diff --git a/gafl/openfold/data/parsers.py b/gafl/openfold/data/parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0574c6e86f5c13d8235b16a61cefa365f0ab5b --- /dev/null +++ b/gafl/openfold/data/parsers.py @@ -0,0 +1,388 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for parsing various file formats.""" +import collections +import dataclasses +import re +import string +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + + +DeletionMatrix = Sequence[Sequence[int]] + + +@dataclasses.dataclass(frozen=True) +class TemplateHit: + """Class representing a template hit.""" + + index: int + name: str + aligned_cols: int + sum_probs: float + query: str + hit_sequence: str + indices_query: List[int] + indices_hit: List[int] + + +def parse_fasta(fasta_string: str) -> Tuple[Sequence[str], Sequence[str]]: + """Parses FASTA string and returns list of strings with amino-acid sequences. + + Arguments: + fasta_string: The string contents of a FASTA file. + + Returns: + A tuple of two lists: + * A list of sequences. + * A list of sequence descriptions taken from the comment lines. In the + same order as the sequences. + """ + sequences = [] + descriptions = [] + index = -1 + for line in fasta_string.splitlines(): + line = line.strip() + if line.startswith(">"): + index += 1 + descriptions.append(line[1:]) # Remove the '>' at the beginning. + sequences.append("") + continue + elif not line: + continue # Skip blank lines. + sequences[index] += line + + return sequences, descriptions + + +def parse_stockholm( + stockholm_string: str, +) -> Tuple[Sequence[str], DeletionMatrix, Sequence[str]]: + """Parses sequences and deletion matrix from stockholm format alignment. + + Args: + stockholm_string: The string contents of a stockholm file. The first + sequence in the file should be the query sequence. + + Returns: + A tuple of: + * A list of sequences that have been aligned to the query. These + might contain duplicates. + * The deletion matrix for the alignment as a list of lists. The element + at `deletion_matrix[i][j]` is the number of residues deleted from + the aligned sequence i at residue position j. + * The names of the targets matched, including the jackhmmer subsequence + suffix. + """ + name_to_sequence = collections.OrderedDict() + for line in stockholm_string.splitlines(): + line = line.strip() + if not line or line.startswith(("#", "//")): + continue + name, sequence = line.split() + if name not in name_to_sequence: + name_to_sequence[name] = "" + name_to_sequence[name] += sequence + + msa = [] + deletion_matrix = [] + + query = "" + keep_columns = [] + for seq_index, sequence in enumerate(name_to_sequence.values()): + if seq_index == 0: + # Gather the columns with gaps from the query + query = sequence + keep_columns = [i for i, res in enumerate(query) if res != "-"] + + # Remove the columns with gaps in the query from all sequences. + aligned_sequence = "".join([sequence[c] for c in keep_columns]) + + msa.append(aligned_sequence) + + # Count the number of deletions w.r.t. query. + deletion_vec = [] + deletion_count = 0 + for seq_res, query_res in zip(sequence, query): + if seq_res != "-" or query_res != "-": + if query_res == "-": + deletion_count += 1 + else: + deletion_vec.append(deletion_count) + deletion_count = 0 + deletion_matrix.append(deletion_vec) + + return msa, deletion_matrix, list(name_to_sequence.keys()) + + +def parse_a3m(a3m_string: str) -> Tuple[Sequence[str], DeletionMatrix]: + """Parses sequences and deletion matrix from a3m format alignment. + + Args: + a3m_string: The string contents of a a3m file. The first sequence in the + file should be the query sequence. + + Returns: + A tuple of: + * A list of sequences that have been aligned to the query. These + might contain duplicates. + * The deletion matrix for the alignment as a list of lists. The element + at `deletion_matrix[i][j]` is the number of residues deleted from + the aligned sequence i at residue position j. + """ + sequences, _ = parse_fasta(a3m_string) + deletion_matrix = [] + for msa_sequence in sequences: + deletion_vec = [] + deletion_count = 0 + for j in msa_sequence: + if j.islower(): + deletion_count += 1 + else: + deletion_vec.append(deletion_count) + deletion_count = 0 + deletion_matrix.append(deletion_vec) + + # Make the MSA matrix out of aligned (deletion-free) sequences. + deletion_table = str.maketrans("", "", string.ascii_lowercase) + aligned_sequences = [s.translate(deletion_table) for s in sequences] + return aligned_sequences, deletion_matrix + + +def _convert_sto_seq_to_a3m( + query_non_gaps: Sequence[bool], sto_seq: str +) -> Iterable[str]: + for is_query_res_non_gap, sequence_res in zip(query_non_gaps, sto_seq): + if is_query_res_non_gap: + yield sequence_res + elif sequence_res != "-": + yield sequence_res.lower() + + +def convert_stockholm_to_a3m( + stockholm_format: str, max_sequences: Optional[int] = None +) -> str: + """Converts MSA in Stockholm format to the A3M format.""" + descriptions = {} + sequences = {} + reached_max_sequences = False + + for line in stockholm_format.splitlines(): + reached_max_sequences = ( + max_sequences and len(sequences) >= max_sequences + ) + if line.strip() and not line.startswith(("#", "//")): + # Ignore blank lines, markup and end symbols - remainder are alignment + # sequence parts. + seqname, aligned_seq = line.split(maxsplit=1) + if seqname not in sequences: + if reached_max_sequences: + continue + sequences[seqname] = "" + sequences[seqname] += aligned_seq + + for line in stockholm_format.splitlines(): + if line[:4] == "#=GS": + # Description row - example format is: + # #=GS UniRef90_Q9H5Z4/4-78 DE [subseq from] cDNA: FLJ22755 ... + columns = line.split(maxsplit=3) + seqname, feature = columns[1:3] + value = columns[3] if len(columns) == 4 else "" + if feature != "DE": + continue + if reached_max_sequences and seqname not in sequences: + continue + descriptions[seqname] = value + if len(descriptions) == len(sequences): + break + + # Convert sto format to a3m line by line + a3m_sequences = {} + # query_sequence is assumed to be the first sequence + query_sequence = next(iter(sequences.values())) + query_non_gaps = [res != "-" for res in query_sequence] + for seqname, sto_sequence in sequences.items(): + a3m_sequences[seqname] = "".join( + _convert_sto_seq_to_a3m(query_non_gaps, sto_sequence) + ) + + fasta_chunks = ( + f">{k} {descriptions.get(k, '')}\n{a3m_sequences[k]}" + for k in a3m_sequences + ) + return "\n".join(fasta_chunks) + "\n" # Include terminating newline. + + +def _get_hhr_line_regex_groups( + regex_pattern: str, line: str +) -> Sequence[Optional[str]]: + match = re.match(regex_pattern, line) + if match is None: + raise RuntimeError(f"Could not parse query line {line}") + return match.groups() + + +def _update_hhr_residue_indices_list( + sequence: str, start_index: int, indices_list: List[int] +): + """Computes the relative indices for each residue with respect to the original sequence.""" + counter = start_index + for symbol in sequence: + if symbol == "-": + indices_list.append(-1) + else: + indices_list.append(counter) + counter += 1 + + +def _parse_hhr_hit(detailed_lines: Sequence[str]) -> TemplateHit: + """Parses the detailed HMM HMM comparison section for a single Hit. + + This works on .hhr files generated from both HHBlits and HHSearch. + + Args: + detailed_lines: A list of lines from a single comparison section between 2 + sequences (which each have their own HMM's) + + Returns: + A dictionary with the information from that detailed comparison section + + Raises: + RuntimeError: If a certain line cannot be processed + """ + # Parse first 2 lines. + number_of_hit = int(detailed_lines[0].split()[-1]) + name_hit = detailed_lines[1][1:] + + # Parse the summary line. + pattern = ( + "Probab=(.*)[\t ]*E-value=(.*)[\t ]*Score=(.*)[\t ]*Aligned_cols=(.*)[\t" + " ]*Identities=(.*)%[\t ]*Similarity=(.*)[\t ]*Sum_probs=(.*)[\t " + "]*Template_Neff=(.*)" + ) + match = re.match(pattern, detailed_lines[2]) + if match is None: + raise RuntimeError( + "Could not parse section: %s. Expected this: \n%s to contain summary." + % (detailed_lines, detailed_lines[2]) + ) + (prob_true, e_value, _, aligned_cols, _, _, sum_probs, neff) = [ + float(x) for x in match.groups() + ] + + # The next section reads the detailed comparisons. These are in a 'human + # readable' format which has a fixed length. The strategy employed is to + # assume that each block starts with the query sequence line, and to parse + # that with a regexp in order to deduce the fixed length used for that block. + query = "" + hit_sequence = "" + indices_query = [] + indices_hit = [] + length_block = None + + for line in detailed_lines[3:]: + # Parse the query sequence line + if ( + line.startswith("Q ") + and not line.startswith("Q ss_dssp") + and not line.startswith("Q ss_pred") + and not line.startswith("Q Consensus") + ): + # Thus the first 17 characters must be 'Q ', and we can parse + # everything after that. + # start sequence end total_sequence_length + patt = r"[\t ]*([0-9]*) ([A-Z-]*)[\t ]*([0-9]*) \([0-9]*\)" + groups = _get_hhr_line_regex_groups(patt, line[17:]) + + # Get the length of the parsed block using the start and finish indices, + # and ensure it is the same as the actual block length. + start = int(groups[0]) - 1 # Make index zero based. + delta_query = groups[1] + end = int(groups[2]) + num_insertions = len([x for x in delta_query if x == "-"]) + length_block = end - start + num_insertions + assert length_block == len(delta_query) + + # Update the query sequence and indices list. + query += delta_query + _update_hhr_residue_indices_list(delta_query, start, indices_query) + + elif line.startswith("T "): + # Parse the hit sequence. + if ( + not line.startswith("T ss_dssp") + and not line.startswith("T ss_pred") + and not line.startswith("T Consensus") + ): + # Thus the first 17 characters must be 'T ', and we can + # parse everything after that. + # start sequence end total_sequence_length + patt = r"[\t ]*([0-9]*) ([A-Z-]*)[\t ]*[0-9]* \([0-9]*\)" + groups = _get_hhr_line_regex_groups(patt, line[17:]) + start = int(groups[0]) - 1 # Make index zero based. + delta_hit_sequence = groups[1] + assert length_block == len(delta_hit_sequence) + + # Update the hit sequence and indices list. + hit_sequence += delta_hit_sequence + _update_hhr_residue_indices_list( + delta_hit_sequence, start, indices_hit + ) + + return TemplateHit( + index=number_of_hit, + name=name_hit, + aligned_cols=int(aligned_cols), + sum_probs=sum_probs, + query=query, + hit_sequence=hit_sequence, + indices_query=indices_query, + indices_hit=indices_hit, + ) + + +def parse_hhr(hhr_string: str) -> Sequence[TemplateHit]: + """Parses the content of an entire HHR file.""" + lines = hhr_string.splitlines() + + # Each .hhr file starts with a results table, then has a sequence of hit + # "paragraphs", each paragraph starting with a line 'No '. We + # iterate through each paragraph to parse each hit. + + block_starts = [i for i, line in enumerate(lines) if line.startswith("No ")] + + hits = [] + if block_starts: + block_starts.append(len(lines)) # Add the end of the final block. + for i in range(len(block_starts) - 1): + hits.append( + _parse_hhr_hit(lines[block_starts[i] : block_starts[i + 1]]) + ) + return hits + + +def parse_e_values_from_tblout(tblout: str) -> Dict[str, float]: + """Parse target to e-value mapping parsed from Jackhmmer tblout string.""" + e_values = {"query": 0} + lines = [line for line in tblout.splitlines() if line[0] != "#"] + # As per http://eddylab.org/software/hmmer/Userguide.pdf fields are + # space-delimited. Relevant fields are (1) target name: and + # (5) E-value (full sequence) (numbering from 1). + for line in lines: + fields = line.split() + e_value = fields[4] + target_name = fields[0] + e_values[target_name] = float(e_value) + return e_values diff --git a/gafl/openfold/data/templates.py b/gafl/openfold/data/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..3071433826e50296818ed5d11d58b92f0bac36b2 --- /dev/null +++ b/gafl/openfold/data/templates.py @@ -0,0 +1,1107 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for getting templates and calculating template features.""" +import dataclasses +import datetime +import glob +import json +import logging +import os +import re +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple + +import numpy as np + +from openfold.data import parsers, mmcif_parsing +from openfold.data.errors import Error +from openfold.data.tools import kalign +from openfold.data.tools.utils import to_date +from openfold.np import residue_constants + + +class NoChainsError(Error): + """An error indicating that template mmCIF didn't have any chains.""" + + +class SequenceNotInTemplateError(Error): + """An error indicating that template mmCIF didn't contain the sequence.""" + + +class NoAtomDataInTemplateError(Error): + """An error indicating that template mmCIF didn't contain atom positions.""" + + +class TemplateAtomMaskAllZerosError(Error): + """An error indicating that template mmCIF had all atom positions masked.""" + + +class QueryToTemplateAlignError(Error): + """An error indicating that the query can't be aligned to the template.""" + + +class CaDistanceError(Error): + """An error indicating that a CA atom distance exceeds a threshold.""" + + +# Prefilter exceptions. +class PrefilterError(Exception): + """A base class for template prefilter exceptions.""" + + +class DateError(PrefilterError): + """An error indicating that the hit date was after the max allowed date.""" + + +class PdbIdError(PrefilterError): + """An error indicating that the hit PDB ID was identical to the query.""" + + +class AlignRatioError(PrefilterError): + """An error indicating that the hit align ratio to the query was too small.""" + + +class DuplicateError(PrefilterError): + """An error indicating that the hit was an exact subsequence of the query.""" + + +class LengthError(PrefilterError): + """An error indicating that the hit was too short.""" + + +TEMPLATE_FEATURES = { + "template_aatype": np.int64, + "template_all_atom_mask": np.float32, + "template_all_atom_positions": np.float32, + "template_domain_names": np.object, + "template_sequence": np.object, + "template_sum_probs": np.float32, +} + + +def _get_pdb_id_and_chain(hit: parsers.TemplateHit) -> Tuple[str, str]: + """Returns PDB id and chain id for an HHSearch Hit.""" + # PDB ID: 4 letters. Chain ID: 1+ alphanumeric letters or "." if unknown. + id_match = re.match(r"[a-zA-Z\d]{4}_[a-zA-Z0-9.]+", hit.name) + if not id_match: + raise ValueError(f"hit.name did not start with PDBID_chain: {hit.name}") + pdb_id, chain_id = id_match.group(0).split("_") + return pdb_id.lower(), chain_id + + +def _is_after_cutoff( + pdb_id: str, + release_dates: Mapping[str, datetime.datetime], + release_date_cutoff: Optional[datetime.datetime], +) -> bool: + """Checks if the template date is after the release date cutoff. + + Args: + pdb_id: 4 letter pdb code. + release_dates: Dictionary mapping PDB ids to their structure release dates. + release_date_cutoff: Max release date that is valid for this query. + + Returns: + True if the template release date is after the cutoff, False otherwise. + """ + pdb_id_upper = pdb_id.upper() + if release_date_cutoff is None: + raise ValueError("The release_date_cutoff must not be None.") + if pdb_id_upper in release_dates: + return release_dates[pdb_id_upper] > release_date_cutoff + else: + # Since this is just a quick prefilter to reduce the number of mmCIF files + # we need to parse, we don't have to worry about returning True here. + logging.info( + "Template structure not in release dates dict: %s", pdb_id + ) + return False + + +def _parse_obsolete(obsolete_file_path: str) -> Mapping[str, str]: + """Parses the data file from PDB that lists which PDB ids are obsolete.""" + with open(obsolete_file_path) as f: + result = {} + for line in f: + line = line.strip() + # We skip obsolete entries that don't contain a mapping to a new entry. + if line.startswith("OBSLTE") and len(line) > 30: + # Format: Date From To + # 'OBSLTE 31-JUL-94 116L 216L' + from_id = line[20:24].lower() + to_id = line[29:33].lower() + result[from_id] = to_id + return result + + +def generate_release_dates_cache(mmcif_dir: str, out_path: str): + dates = {} + for f in os.listdir(mmcif_dir): + if f.endswith(".cif"): + path = os.path.join(mmcif_dir, f) + with open(path, "r") as fp: + mmcif_string = fp.read() + + file_id = os.path.splitext(f)[0] + mmcif = mmcif_parsing.parse( + file_id=file_id, mmcif_string=mmcif_string + ) + if mmcif.mmcif_object is None: + logging.info(f"Failed to parse {f}. Skipping...") + continue + + mmcif = mmcif.mmcif_object + release_date = mmcif.header["release_date"] + + dates[file_id] = release_date + + with open(out_path, "r") as fp: + fp.write(json.dumps(dates)) + + +def _parse_release_dates(path: str) -> Mapping[str, datetime.datetime]: + """Parses release dates file, returns a mapping from PDBs to release dates.""" + with open(path, "r") as fp: + data = json.load(fp) + + return { + pdb.upper(): to_date(v) + for pdb, d in data.items() + for k, v in d.items() + if k == "release_date" + } + + +def _assess_hhsearch_hit( + hit: parsers.TemplateHit, + hit_pdb_code: str, + query_sequence: str, + query_pdb_code: Optional[str], + release_dates: Mapping[str, datetime.datetime], + release_date_cutoff: datetime.datetime, + max_subsequence_ratio: float = 0.95, + min_align_ratio: float = 0.1, +) -> bool: + """Determines if template is valid (without parsing the template mmcif file). + + Args: + hit: HhrHit for the template. + hit_pdb_code: The 4 letter pdb code of the template hit. This might be + different from the value in the actual hit since the original pdb might + have become obsolete. + query_sequence: Amino acid sequence of the query. + query_pdb_code: 4 letter pdb code of the query. + release_dates: Dictionary mapping pdb codes to their structure release + dates. + release_date_cutoff: Max release date that is valid for this query. + max_subsequence_ratio: Exclude any exact matches with this much overlap. + min_align_ratio: Minimum overlap between the template and query. + + Returns: + True if the hit passed the prefilter. Raises an exception otherwise. + + Raises: + DateError: If the hit date was after the max allowed date. + PdbIdError: If the hit PDB ID was identical to the query. + AlignRatioError: If the hit align ratio to the query was too small. + DuplicateError: If the hit was an exact subsequence of the query. + LengthError: If the hit was too short. + """ + aligned_cols = hit.aligned_cols + align_ratio = aligned_cols / len(query_sequence) + + template_sequence = hit.hit_sequence.replace("-", "") + length_ratio = float(len(template_sequence)) / len(query_sequence) + + # Check whether the template is a large subsequence or duplicate of original + # query. This can happen due to duplicate entries in the PDB database. + duplicate = ( + template_sequence in query_sequence + and length_ratio > max_subsequence_ratio + ) + + if _is_after_cutoff(hit_pdb_code, release_dates, release_date_cutoff): + date = release_dates[hit_pdb_code.upper()] + raise DateError( + f"Date ({date}) > max template date " + f"({release_date_cutoff})." + ) + + if query_pdb_code is not None: + if query_pdb_code.lower() == hit_pdb_code.lower(): + raise PdbIdError("PDB code identical to Query PDB code.") + + if align_ratio <= min_align_ratio: + raise AlignRatioError( + "Proportion of residues aligned to query too small. " + f"Align ratio: {align_ratio}." + ) + + if duplicate: + raise DuplicateError( + "Template is an exact subsequence of query with large " + f"coverage. Length ratio: {length_ratio}." + ) + + if len(template_sequence) < 10: + raise LengthError( + f"Template too short. Length: {len(template_sequence)}." + ) + + return True + + +def _find_template_in_pdb( + template_chain_id: str, + template_sequence: str, + mmcif_object: mmcif_parsing.MmcifObject, +) -> Tuple[str, str, int]: + """Tries to find the template chain in the given pdb file. + + This method tries the three following things in order: + 1. Tries if there is an exact match in both the chain ID and the sequence. + If yes, the chain sequence is returned. Otherwise: + 2. Tries if there is an exact match only in the sequence. + If yes, the chain sequence is returned. Otherwise: + 3. Tries if there is a fuzzy match (X = wildcard) in the sequence. + If yes, the chain sequence is returned. + If none of these succeed, a SequenceNotInTemplateError is thrown. + + Args: + template_chain_id: The template chain ID. + template_sequence: The template chain sequence. + mmcif_object: The PDB object to search for the template in. + + Returns: + A tuple with: + * The chain sequence that was found to match the template in the PDB object. + * The ID of the chain that is being returned. + * The offset where the template sequence starts in the chain sequence. + + Raises: + SequenceNotInTemplateError: If no match is found after the steps described + above. + """ + # Try if there is an exact match in both the chain ID and the (sub)sequence. + pdb_id = mmcif_object.file_id + chain_sequence = mmcif_object.chain_to_seqres.get(template_chain_id) + if chain_sequence and (template_sequence in chain_sequence): + logging.info( + "Found an exact template match %s_%s.", pdb_id, template_chain_id + ) + mapping_offset = chain_sequence.find(template_sequence) + return chain_sequence, template_chain_id, mapping_offset + + # Try if there is an exact match in the (sub)sequence only. + for chain_id, chain_sequence in mmcif_object.chain_to_seqres.items(): + if chain_sequence and (template_sequence in chain_sequence): + logging.info("Found a sequence-only match %s_%s.", pdb_id, chain_id) + mapping_offset = chain_sequence.find(template_sequence) + return chain_sequence, chain_id, mapping_offset + + # Return a chain sequence that fuzzy matches (X = wildcard) the template. + # Make parentheses unnamed groups (?:_) to avoid the 100 named groups limit. + regex = ["." if aa == "X" else "(?:%s|X)" % aa for aa in template_sequence] + regex = re.compile("".join(regex)) + for chain_id, chain_sequence in mmcif_object.chain_to_seqres.items(): + match = re.search(regex, chain_sequence) + if match: + logging.info( + "Found a fuzzy sequence-only match %s_%s.", pdb_id, chain_id + ) + mapping_offset = match.start() + return chain_sequence, chain_id, mapping_offset + + # No hits, raise an error. + raise SequenceNotInTemplateError( + "Could not find the template sequence in %s_%s. Template sequence: %s, " + "chain_to_seqres: %s" + % ( + pdb_id, + template_chain_id, + template_sequence, + mmcif_object.chain_to_seqres, + ) + ) + + +def _realign_pdb_template_to_query( + old_template_sequence: str, + template_chain_id: str, + mmcif_object: mmcif_parsing.MmcifObject, + old_mapping: Mapping[int, int], + kalign_binary_path: str, +) -> Tuple[str, Mapping[int, int]]: + """Aligns template from the mmcif_object to the query. + + In case PDB70 contains a different version of the template sequence, we need + to perform a realignment to the actual sequence that is in the mmCIF file. + This method performs such realignment, but returns the new sequence and + mapping only if the sequence in the mmCIF file is 90% identical to the old + sequence. + + Note that the old_template_sequence comes from the hit, and contains only that + part of the chain that matches with the query while the new_template_sequence + is the full chain. + + Args: + old_template_sequence: The template sequence that was returned by the PDB + template search (typically done using HHSearch). + template_chain_id: The template chain id was returned by the PDB template + search (typically done using HHSearch). This is used to find the right + chain in the mmcif_object chain_to_seqres mapping. + mmcif_object: A mmcif_object which holds the actual template data. + old_mapping: A mapping from the query sequence to the template sequence. + This mapping will be used to compute the new mapping from the query + sequence to the actual mmcif_object template sequence by aligning the + old_template_sequence and the actual template sequence. + kalign_binary_path: The path to a kalign executable. + + Returns: + A tuple (new_template_sequence, new_query_to_template_mapping) where: + * new_template_sequence is the actual template sequence that was found in + the mmcif_object. + * new_query_to_template_mapping is the new mapping from the query to the + actual template found in the mmcif_object. + + Raises: + QueryToTemplateAlignError: + * If there was an error thrown by the alignment tool. + * Or if the actual template sequence differs by more than 10% from the + old_template_sequence. + """ + aligner = kalign.Kalign(binary_path=kalign_binary_path) + new_template_sequence = mmcif_object.chain_to_seqres.get( + template_chain_id, "" + ) + + # Sometimes the template chain id is unknown. But if there is only a single + # sequence within the mmcif_object, it is safe to assume it is that one. + if not new_template_sequence: + if len(mmcif_object.chain_to_seqres) == 1: + logging.info( + "Could not find %s in %s, but there is only 1 sequence, so " + "using that one.", + template_chain_id, + mmcif_object.file_id, + ) + new_template_sequence = list(mmcif_object.chain_to_seqres.values())[ + 0 + ] + else: + raise QueryToTemplateAlignError( + f"Could not find chain {template_chain_id} in {mmcif_object.file_id}. " + "If there are no mmCIF parsing errors, it is possible it was not a " + "protein chain." + ) + + try: + (old_aligned_template, new_aligned_template), _ = parsers.parse_a3m( + aligner.align([old_template_sequence, new_template_sequence]) + ) + except Exception as e: + raise QueryToTemplateAlignError( + "Could not align old template %s to template %s (%s_%s). Error: %s" + % ( + old_template_sequence, + new_template_sequence, + mmcif_object.file_id, + template_chain_id, + str(e), + ) + ) + + logging.info( + "Old aligned template: %s\nNew aligned template: %s", + old_aligned_template, + new_aligned_template, + ) + + old_to_new_template_mapping = {} + old_template_index = -1 + new_template_index = -1 + num_same = 0 + for old_template_aa, new_template_aa in zip( + old_aligned_template, new_aligned_template + ): + if old_template_aa != "-": + old_template_index += 1 + if new_template_aa != "-": + new_template_index += 1 + if old_template_aa != "-" and new_template_aa != "-": + old_to_new_template_mapping[old_template_index] = new_template_index + if old_template_aa == new_template_aa: + num_same += 1 + + # Require at least 90 % sequence identity wrt to the shorter of the sequences. + if ( + float(num_same) + / min(len(old_template_sequence), len(new_template_sequence)) + < 0.9 + ): + raise QueryToTemplateAlignError( + "Insufficient similarity of the sequence in the database: %s to the " + "actual sequence in the mmCIF file %s_%s: %s. We require at least " + "90 %% similarity wrt to the shorter of the sequences. This is not a " + "problem unless you think this is a template that should be included." + % ( + old_template_sequence, + mmcif_object.file_id, + template_chain_id, + new_template_sequence, + ) + ) + + new_query_to_template_mapping = {} + for query_index, old_template_index in old_mapping.items(): + new_query_to_template_mapping[ + query_index + ] = old_to_new_template_mapping.get(old_template_index, -1) + + new_template_sequence = new_template_sequence.replace("-", "") + + return new_template_sequence, new_query_to_template_mapping + + +def _check_residue_distances( + all_positions: np.ndarray, + all_positions_mask: np.ndarray, + max_ca_ca_distance: float, +): + """Checks if the distance between unmasked neighbor residues is ok.""" + ca_position = residue_constants.atom_order["CA"] + prev_is_unmasked = False + prev_calpha = None + for i, (coords, mask) in enumerate(zip(all_positions, all_positions_mask)): + this_is_unmasked = bool(mask[ca_position]) + if this_is_unmasked: + this_calpha = coords[ca_position] + if prev_is_unmasked: + distance = np.linalg.norm(this_calpha - prev_calpha) + if distance > max_ca_ca_distance: + raise CaDistanceError( + "The distance between residues %d and %d is %f > limit %f." + % (i, i + 1, distance, max_ca_ca_distance) + ) + prev_calpha = this_calpha + prev_is_unmasked = this_is_unmasked + + +def _get_atom_positions( + mmcif_object: mmcif_parsing.MmcifObject, + auth_chain_id: str, + max_ca_ca_distance: float, + _zero_center_positions: bool = True, +) -> Tuple[np.ndarray, np.ndarray]: + """Gets atom positions and mask from a list of Biopython Residues.""" + coords_with_mask = mmcif_parsing.get_atom_coords( + mmcif_object=mmcif_object, + chain_id=auth_chain_id, + _zero_center_positions=_zero_center_positions, + ) + all_atom_positions, all_atom_mask = coords_with_mask + _check_residue_distances( + all_atom_positions, all_atom_mask, max_ca_ca_distance + ) + return all_atom_positions, all_atom_mask + + +def _extract_template_features( + mmcif_object: mmcif_parsing.MmcifObject, + pdb_id: str, + mapping: Mapping[int, int], + template_sequence: str, + query_sequence: str, + template_chain_id: str, + kalign_binary_path: str, + _zero_center_positions: bool = True, +) -> Tuple[Dict[str, Any], Optional[str]]: + """Parses atom positions in the target structure and aligns with the query. + + Atoms for each residue in the template structure are indexed to coincide + with their corresponding residue in the query sequence, according to the + alignment mapping provided. + + Args: + mmcif_object: mmcif_parsing.MmcifObject representing the template. + pdb_id: PDB code for the template. + mapping: Dictionary mapping indices in the query sequence to indices in + the template sequence. + template_sequence: String describing the amino acid sequence for the + template protein. + query_sequence: String describing the amino acid sequence for the query + protein. + template_chain_id: String ID describing which chain in the structure proto + should be used. + kalign_binary_path: The path to a kalign executable used for template + realignment. + + Returns: + A tuple with: + * A dictionary containing the extra features derived from the template + protein structure. + * A warning message if the hit was realigned to the actual mmCIF sequence. + Otherwise None. + + Raises: + NoChainsError: If the mmcif object doesn't contain any chains. + SequenceNotInTemplateError: If the given chain id / sequence can't + be found in the mmcif object. + QueryToTemplateAlignError: If the actual template in the mmCIF file + can't be aligned to the query. + NoAtomDataInTemplateError: If the mmcif object doesn't contain + atom positions. + TemplateAtomMaskAllZerosError: If the mmcif object doesn't have any + unmasked residues. + """ + if mmcif_object is None or not mmcif_object.chain_to_seqres: + raise NoChainsError( + "No chains in PDB: %s_%s" % (pdb_id, template_chain_id) + ) + + warning = None + try: + seqres, chain_id, mapping_offset = _find_template_in_pdb( + template_chain_id=template_chain_id, + template_sequence=template_sequence, + mmcif_object=mmcif_object, + ) + except SequenceNotInTemplateError: + # If PDB70 contains a different version of the template, we use the sequence + # from the mmcif_object. + chain_id = template_chain_id + warning = ( + f"The exact sequence {template_sequence} was not found in " + f"{pdb_id}_{chain_id}. Realigning the template to the actual sequence." + ) + logging.warning(warning) + # This throws an exception if it fails to realign the hit. + seqres, mapping = _realign_pdb_template_to_query( + old_template_sequence=template_sequence, + template_chain_id=template_chain_id, + mmcif_object=mmcif_object, + old_mapping=mapping, + kalign_binary_path=kalign_binary_path, + ) + logging.info( + "Sequence in %s_%s: %s successfully realigned to %s", + pdb_id, + chain_id, + template_sequence, + seqres, + ) + # The template sequence changed. + template_sequence = seqres + # No mapping offset, the query is aligned to the actual sequence. + mapping_offset = 0 + + try: + # Essentially set to infinity - we don't want to reject templates unless + # they're really really bad. + all_atom_positions, all_atom_mask = _get_atom_positions( + mmcif_object, + chain_id, + max_ca_ca_distance=150.0, + _zero_center_positions=_zero_center_positions, + ) + except (CaDistanceError, KeyError) as ex: + raise NoAtomDataInTemplateError( + "Could not get atom data (%s_%s): %s" % (pdb_id, chain_id, str(ex)) + ) from ex + + all_atom_positions = np.split( + all_atom_positions, all_atom_positions.shape[0] + ) + all_atom_masks = np.split(all_atom_mask, all_atom_mask.shape[0]) + + output_templates_sequence = [] + templates_all_atom_positions = [] + templates_all_atom_masks = [] + + for _ in query_sequence: + # Residues in the query_sequence that are not in the template_sequence: + templates_all_atom_positions.append( + np.zeros((residue_constants.atom_type_num, 3)) + ) + templates_all_atom_masks.append( + np.zeros(residue_constants.atom_type_num) + ) + output_templates_sequence.append("-") + + for k, v in mapping.items(): + template_index = v + mapping_offset + templates_all_atom_positions[k] = all_atom_positions[template_index][0] + templates_all_atom_masks[k] = all_atom_masks[template_index][0] + output_templates_sequence[k] = template_sequence[v] + + # Alanine (AA with the lowest number of atoms) has 5 atoms (C, CA, CB, N, O). + if np.sum(templates_all_atom_masks) < 5: + raise TemplateAtomMaskAllZerosError( + "Template all atom mask was all zeros: %s_%s. Residue range: %d-%d" + % ( + pdb_id, + chain_id, + min(mapping.values()) + mapping_offset, + max(mapping.values()) + mapping_offset, + ) + ) + + output_templates_sequence = "".join(output_templates_sequence) + + templates_aatype = residue_constants.sequence_to_onehot( + output_templates_sequence, residue_constants.HHBLITS_AA_TO_ID + ) + + return ( + { + "template_all_atom_positions": np.array( + templates_all_atom_positions + ), + "template_all_atom_mask": np.array(templates_all_atom_masks), + "template_sequence": output_templates_sequence.encode(), + "template_aatype": np.array(templates_aatype), + "template_domain_names": f"{pdb_id.lower()}_{chain_id}".encode(), + }, + warning, + ) + + +def _build_query_to_hit_index_mapping( + hit_query_sequence: str, + hit_sequence: str, + indices_hit: Sequence[int], + indices_query: Sequence[int], + original_query_sequence: str, +) -> Mapping[int, int]: + """Gets mapping from indices in original query sequence to indices in the hit. + + hit_query_sequence and hit_sequence are two aligned sequences containing gap + characters. hit_query_sequence contains only the part of the original query + sequence that matched the hit. When interpreting the indices from the .hhr, we + need to correct for this to recover a mapping from original query sequence to + the hit sequence. + + Args: + hit_query_sequence: The portion of the query sequence that is in the .hhr + hit + hit_sequence: The portion of the hit sequence that is in the .hhr + indices_hit: The indices for each aminoacid relative to the hit sequence + indices_query: The indices for each aminoacid relative to the original query + sequence + original_query_sequence: String describing the original query sequence. + + Returns: + Dictionary with indices in the original query sequence as keys and indices + in the hit sequence as values. + """ + # If the hit is empty (no aligned residues), return empty mapping + if not hit_query_sequence: + return {} + + # Remove gaps and find the offset of hit.query relative to original query. + hhsearch_query_sequence = hit_query_sequence.replace("-", "") + hit_sequence = hit_sequence.replace("-", "") + hhsearch_query_offset = original_query_sequence.find( + hhsearch_query_sequence + ) + + # Index of -1 used for gap characters. Subtract the min index ignoring gaps. + min_idx = min(x for x in indices_hit if x > -1) + fixed_indices_hit = [x - min_idx if x > -1 else -1 for x in indices_hit] + + min_idx = min(x for x in indices_query if x > -1) + fixed_indices_query = [x - min_idx if x > -1 else -1 for x in indices_query] + + # Zip the corrected indices, ignore case where both seqs have gap characters. + mapping = {} + for q_i, q_t in zip(fixed_indices_query, fixed_indices_hit): + if q_t != -1 and q_i != -1: + if q_t >= len(hit_sequence) or q_i + hhsearch_query_offset >= len( + original_query_sequence + ): + continue + mapping[q_i + hhsearch_query_offset] = q_t + + return mapping + + +@dataclasses.dataclass(frozen=True) +class PrefilterResult: + valid: bool + error: Optional[str] + warning: Optional[str] + +@dataclasses.dataclass(frozen=True) +class SingleHitResult: + features: Optional[Mapping[str, Any]] + error: Optional[str] + warning: Optional[str] + + +def _prefilter_hit( + query_sequence: str, + query_pdb_code: Optional[str], + hit: parsers.TemplateHit, + max_template_date: datetime.datetime, + release_dates: Mapping[str, datetime.datetime], + obsolete_pdbs: Mapping[str, str], + strict_error_check: bool = False, +): + # Fail hard if we can't get the PDB ID and chain name from the hit. + hit_pdb_code, hit_chain_id = _get_pdb_id_and_chain(hit) + + if hit_pdb_code not in release_dates: + if hit_pdb_code in obsolete_pdbs: + hit_pdb_code = obsolete_pdbs[hit_pdb_code] + + # Pass hit_pdb_code since it might have changed due to the pdb being + # obsolete. + try: + _assess_hhsearch_hit( + hit=hit, + hit_pdb_code=hit_pdb_code, + query_sequence=query_sequence, + query_pdb_code=query_pdb_code, + release_dates=release_dates, + release_date_cutoff=max_template_date, + ) + except PrefilterError as e: + hit_name = f"{hit_pdb_code}_{hit_chain_id}" + msg = f"hit {hit_name} did not pass prefilter: {str(e)}" + logging.info("%s: %s", query_pdb_code, msg) + if strict_error_check and isinstance( + e, (DateError, PdbIdError, DuplicateError) + ): + # In strict mode we treat some prefilter cases as errors. + return PrefilterResult(valid=False, error=msg, warning=None) + + return PrefilterResult(valid=False, error=None, warning=None) + + return PrefilterResult(valid=True, error=None, warning=None) + + +def _process_single_hit( + query_sequence: str, + query_pdb_code: Optional[str], + hit: parsers.TemplateHit, + mmcif_dir: str, + max_template_date: datetime.datetime, + release_dates: Mapping[str, datetime.datetime], + obsolete_pdbs: Mapping[str, str], + kalign_binary_path: str, + strict_error_check: bool = False, + _zero_center_positions: bool = True, +) -> SingleHitResult: + """Tries to extract template features from a single HHSearch hit.""" + # Fail hard if we can't get the PDB ID and chain name from the hit. + hit_pdb_code, hit_chain_id = _get_pdb_id_and_chain(hit) + + if hit_pdb_code not in release_dates: + if hit_pdb_code in obsolete_pdbs: + hit_pdb_code = obsolete_pdbs[hit_pdb_code] + + mapping = _build_query_to_hit_index_mapping( + hit.query, + hit.hit_sequence, + hit.indices_hit, + hit.indices_query, + query_sequence, + ) + + # The mapping is from the query to the actual hit sequence, so we need to + # remove gaps (which regardless have a missing confidence score). + template_sequence = hit.hit_sequence.replace("-", "") + + cif_path = os.path.join(mmcif_dir, hit_pdb_code + ".cif") + logging.info( + "Reading PDB entry from %s. Query: %s, template: %s", + cif_path, + query_sequence, + template_sequence, + ) + # Fail if we can't find the mmCIF file. + with open(cif_path, "r") as cif_file: + cif_string = cif_file.read() + + parsing_result = mmcif_parsing.parse( + file_id=hit_pdb_code, mmcif_string=cif_string + ) + + if parsing_result.mmcif_object is not None: + hit_release_date = datetime.datetime.strptime( + parsing_result.mmcif_object.header["release_date"], "%Y-%m-%d" + ) + if hit_release_date > max_template_date: + error = "Template %s date (%s) > max template date (%s)." % ( + hit_pdb_code, + hit_release_date, + max_template_date, + ) + if strict_error_check: + return SingleHitResult(features=None, error=error, warning=None) + else: + logging.info(error) + return SingleHitResult(features=None, error=None, warning=None) + + try: + features, realign_warning = _extract_template_features( + mmcif_object=parsing_result.mmcif_object, + pdb_id=hit_pdb_code, + mapping=mapping, + template_sequence=template_sequence, + query_sequence=query_sequence, + template_chain_id=hit_chain_id, + kalign_binary_path=kalign_binary_path, + _zero_center_positions=_zero_center_positions, + ) + features["template_sum_probs"] = [hit.sum_probs] + + # It is possible there were some errors when parsing the other chains in the + # mmCIF file, but the template features for the chain we want were still + # computed. In such case the mmCIF parsing errors are not relevant. + return SingleHitResult( + features=features, error=None, warning=realign_warning + ) + except ( + NoChainsError, + NoAtomDataInTemplateError, + TemplateAtomMaskAllZerosError, + ) as e: + # These 3 errors indicate missing mmCIF experimental data rather than a + # problem with the template search, so turn them into warnings. + warning = ( + "%s_%s (sum_probs: %.2f, rank: %d): feature extracting errors: " + "%s, mmCIF parsing errors: %s" + % ( + hit_pdb_code, + hit_chain_id, + hit.sum_probs, + hit.index, + str(e), + parsing_result.errors, + ) + ) + if strict_error_check: + return SingleHitResult(features=None, error=warning, warning=None) + else: + return SingleHitResult(features=None, error=None, warning=warning) + except Error as e: + error = ( + "%s_%s (sum_probs: %.2f, rank: %d): feature extracting errors: " + "%s, mmCIF parsing errors: %s" + % ( + hit_pdb_code, + hit_chain_id, + hit.sum_probs, + hit.index, + str(e), + parsing_result.errors, + ) + ) + return SingleHitResult(features=None, error=error, warning=None) + + +@dataclasses.dataclass(frozen=True) +class TemplateSearchResult: + features: Mapping[str, Any] + errors: Sequence[str] + warnings: Sequence[str] + + +class TemplateHitFeaturizer: + """A class for turning hhr hits to template features.""" + def __init__( + self, + mmcif_dir: str, + max_template_date: str, + max_hits: int, + kalign_binary_path: str, + release_dates_path: Optional[str] = None, + obsolete_pdbs_path: Optional[str] = None, + strict_error_check: bool = False, + _shuffle_top_k_prefiltered: Optional[int] = None, + _zero_center_positions: bool = True, + ): + """Initializes the Template Search. + + Args: + mmcif_dir: Path to a directory with mmCIF structures. Once a template ID + is found by HHSearch, this directory is used to retrieve the template + data. + max_template_date: The maximum date permitted for template structures. No + template with date higher than this date will be returned. In ISO8601 + date format, YYYY-MM-DD. + max_hits: The maximum number of templates that will be returned. + kalign_binary_path: The path to a kalign executable used for template + realignment. + release_dates_path: An optional path to a file with a mapping from PDB IDs + to their release dates. Thanks to this we don't have to redundantly + parse mmCIF files to get that information. + obsolete_pdbs_path: An optional path to a file containing a mapping from + obsolete PDB IDs to the PDB IDs of their replacements. + strict_error_check: If True, then the following will be treated as errors: + * If any template date is after the max_template_date. + * If any template has identical PDB ID to the query. + * If any template is a duplicate of the query. + * Any feature computation errors. + """ + self._mmcif_dir = mmcif_dir + if not glob.glob(os.path.join(self._mmcif_dir, "*.cif")): + logging.error("Could not find CIFs in %s", self._mmcif_dir) + raise ValueError(f"Could not find CIFs in {self._mmcif_dir}") + + try: + self._max_template_date = datetime.datetime.strptime( + max_template_date, "%Y-%m-%d" + ) + except ValueError: + raise ValueError( + "max_template_date must be set and have format YYYY-MM-DD." + ) + self.max_hits = max_hits + self._kalign_binary_path = kalign_binary_path + self._strict_error_check = strict_error_check + + if release_dates_path: + logging.info( + "Using precomputed release dates %s.", release_dates_path + ) + self._release_dates = _parse_release_dates(release_dates_path) + else: + self._release_dates = {} + + if obsolete_pdbs_path: + logging.info( + "Using precomputed obsolete pdbs %s.", obsolete_pdbs_path + ) + self._obsolete_pdbs = _parse_obsolete(obsolete_pdbs_path) + else: + self._obsolete_pdbs = {} + + self._shuffle_top_k_prefiltered = _shuffle_top_k_prefiltered + self._zero_center_positions = _zero_center_positions + + def get_templates( + self, + query_sequence: str, + query_pdb_code: Optional[str], + query_release_date: Optional[datetime.datetime], + hits: Sequence[parsers.TemplateHit], + ) -> TemplateSearchResult: + """Computes the templates for given query sequence (more details above).""" + logging.info("Searching for template for: %s", query_pdb_code) + + template_features = {} + for template_feature_name in TEMPLATE_FEATURES: + template_features[template_feature_name] = [] + + # Always use a max_template_date. Set to query_release_date minus 60 days + # if that's earlier. + template_cutoff_date = self._max_template_date + if query_release_date: + delta = datetime.timedelta(days=60) + if query_release_date - delta < template_cutoff_date: + template_cutoff_date = query_release_date - delta + assert template_cutoff_date < query_release_date + assert template_cutoff_date <= self._max_template_date + + num_hits = 0 + errors = [] + warnings = [] + + filtered = [] + for hit in hits: + prefilter_result = _prefilter_hit( + query_sequence=query_sequence, + query_pdb_code=query_pdb_code, + hit=hit, + max_template_date=template_cutoff_date, + release_dates=self._release_dates, + obsolete_pdbs=self._obsolete_pdbs, + strict_error_check=self._strict_error_check, + ) + + if prefilter_result.error: + errors.append(prefilter_result.error) + + if prefilter_result.warning: + warnings.append(prefilter_result.warning) + + if prefilter_result.valid: + filtered.append(hit) + + filtered = list( + sorted(filtered, key=lambda x: x.sum_probs, reverse=True) + ) + idx = list(range(len(filtered))) + if(self._shuffle_top_k_prefiltered): + stk = self._shuffle_top_k_prefiltered + idx[:stk] = np.random.permutation(idx[:stk]) + + for i in idx: + # We got all the templates we wanted, stop processing hits. + if num_hits >= self.max_hits: + break + + hit = filtered[i] + + result = _process_single_hit( + query_sequence=query_sequence, + query_pdb_code=query_pdb_code, + hit=hit, + mmcif_dir=self._mmcif_dir, + max_template_date=template_cutoff_date, + release_dates=self._release_dates, + obsolete_pdbs=self._obsolete_pdbs, + strict_error_check=self._strict_error_check, + kalign_binary_path=self._kalign_binary_path, + _zero_center_positions=self._zero_center_positions, + ) + + if result.error: + errors.append(result.error) + + # There could be an error even if there are some results, e.g. thrown by + # other unparsable chains in the same mmCIF file. + if result.warning: + warnings.append(result.warning) + + if result.features is None: + logging.info( + "Skipped invalid hit %s, error: %s, warning: %s", + hit.name, + result.error, + result.warning, + ) + else: + # Increment the hit counter, since we got features out of this hit. + num_hits += 1 + for k in template_features: + template_features[k].append(result.features[k]) + + for name in template_features: + if num_hits > 0: + template_features[name] = np.stack( + template_features[name], axis=0 + ).astype(TEMPLATE_FEATURES[name]) + else: + # Make sure the feature has correct dtype even if empty. + template_features[name] = np.array( + [], dtype=TEMPLATE_FEATURES[name] + ) + + return TemplateSearchResult( + features=template_features, errors=errors, warnings=warnings + ) diff --git a/gafl/openfold/data/tools/__init__.py b/gafl/openfold/data/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/openfold/data/tools/hhblits.py b/gafl/openfold/data/tools/hhblits.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1c1e7bfdbf1cf7d6f373f79d8f7d2c354195fb --- /dev/null +++ b/gafl/openfold/data/tools/hhblits.py @@ -0,0 +1,175 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Library to run HHblits from Python.""" +import glob +import logging +import os +import subprocess +from typing import Any, Mapping, Optional, Sequence + +from openfold.data.tools import utils + + +_HHBLITS_DEFAULT_P = 20 +_HHBLITS_DEFAULT_Z = 500 + + +class HHBlits: + """Python wrapper of the HHblits binary.""" + + def __init__( + self, + *, + binary_path: str, + databases: Sequence[str], + n_cpu: int = 4, + n_iter: int = 3, + e_value: float = 0.001, + maxseq: int = 1_000_000, + realign_max: int = 100_000, + maxfilt: int = 100_000, + min_prefilter_hits: int = 1000, + all_seqs: bool = False, + alt: Optional[int] = None, + p: int = _HHBLITS_DEFAULT_P, + z: int = _HHBLITS_DEFAULT_Z, + ): + """Initializes the Python HHblits wrapper. + + Args: + binary_path: The path to the HHblits executable. + databases: A sequence of HHblits database paths. This should be the + common prefix for the database files (i.e. up to but not including + _hhm.ffindex etc.) + n_cpu: The number of CPUs to give HHblits. + n_iter: The number of HHblits iterations. + e_value: The E-value, see HHblits docs for more details. + maxseq: The maximum number of rows in an input alignment. Note that this + parameter is only supported in HHBlits version 3.1 and higher. + realign_max: Max number of HMM-HMM hits to realign. HHblits default: 500. + maxfilt: Max number of hits allowed to pass the 2nd prefilter. + HHblits default: 20000. + min_prefilter_hits: Min number of hits to pass prefilter. + HHblits default: 100. + all_seqs: Return all sequences in the MSA / Do not filter the result MSA. + HHblits default: False. + alt: Show up to this many alternative alignments. + p: Minimum Prob for a hit to be included in the output hhr file. + HHblits default: 20. + z: Hard cap on number of hits reported in the hhr file. + HHblits default: 500. NB: The relevant HHblits flag is -Z not -z. + + Raises: + RuntimeError: If HHblits binary not found within the path. + """ + self.binary_path = binary_path + self.databases = databases + + for database_path in self.databases: + if not glob.glob(database_path + "_*"): + logging.error( + "Could not find HHBlits database %s", database_path + ) + raise ValueError( + f"Could not find HHBlits database {database_path}" + ) + + self.n_cpu = n_cpu + self.n_iter = n_iter + self.e_value = e_value + self.maxseq = maxseq + self.realign_max = realign_max + self.maxfilt = maxfilt + self.min_prefilter_hits = min_prefilter_hits + self.all_seqs = all_seqs + self.alt = alt + self.p = p + self.z = z + + def query(self, input_fasta_path: str) -> Mapping[str, Any]: + """Queries the database using HHblits.""" + with utils.tmpdir_manager(base_dir="/tmp") as query_tmp_dir: + a3m_path = os.path.join(query_tmp_dir, "output.a3m") + + db_cmd = [] + for db_path in self.databases: + db_cmd.append("-d") + db_cmd.append(db_path) + cmd = [ + self.binary_path, + "-i", + input_fasta_path, + "-cpu", + str(self.n_cpu), + "-oa3m", + a3m_path, + "-o", + "/dev/null", + "-n", + str(self.n_iter), + "-e", + str(self.e_value), + "-maxseq", + str(self.maxseq), + "-realign_max", + str(self.realign_max), + "-maxfilt", + str(self.maxfilt), + "-min_prefilter_hits", + str(self.min_prefilter_hits), + ] + if self.all_seqs: + cmd += ["-all"] + if self.alt: + cmd += ["-alt", str(self.alt)] + if self.p != _HHBLITS_DEFAULT_P: + cmd += ["-p", str(self.p)] + if self.z != _HHBLITS_DEFAULT_Z: + cmd += ["-Z", str(self.z)] + cmd += db_cmd + + logging.info('Launching subprocess "%s"', " ".join(cmd)) + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + + with utils.timing("HHblits query"): + stdout, stderr = process.communicate() + retcode = process.wait() + + if retcode: + # Logs have a 15k character limit, so log HHblits error line by line. + logging.error("HHblits failed. HHblits stderr begin:") + for error_line in stderr.decode("utf-8").splitlines(): + if error_line.strip(): + logging.error(error_line.strip()) + logging.error("HHblits stderr end") + raise RuntimeError( + "HHblits failed\nstdout:\n%s\n\nstderr:\n%s\n" + % (stdout.decode("utf-8"), stderr[:500_000].decode("utf-8")) + ) + + with open(a3m_path) as f: + a3m = f.read() + + raw_output = dict( + a3m=a3m, + output=stdout, + stderr=stderr, + n_iter=self.n_iter, + e_value=self.e_value, + ) + return raw_output diff --git a/gafl/openfold/data/tools/hhsearch.py b/gafl/openfold/data/tools/hhsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..d62e3b410c5bcf1e1089d961c8c44aad81d7f2a2 --- /dev/null +++ b/gafl/openfold/data/tools/hhsearch.py @@ -0,0 +1,106 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Library to run HHsearch from Python.""" +import glob +import logging +import os +import subprocess +from typing import Sequence + +from openfold.data.tools import utils + + +class HHSearch: + """Python wrapper of the HHsearch binary.""" + + def __init__( + self, + *, + binary_path: str, + databases: Sequence[str], + n_cpu: int = 2, + maxseq: int = 1_000_000, + ): + """Initializes the Python HHsearch wrapper. + + Args: + binary_path: The path to the HHsearch executable. + databases: A sequence of HHsearch database paths. This should be the + common prefix for the database files (i.e. up to but not including + _hhm.ffindex etc.) + n_cpu: The number of CPUs to use + maxseq: The maximum number of rows in an input alignment. Note that this + parameter is only supported in HHBlits version 3.1 and higher. + + Raises: + RuntimeError: If HHsearch binary not found within the path. + """ + self.binary_path = binary_path + self.databases = databases + self.n_cpu = n_cpu + self.maxseq = maxseq + + for database_path in self.databases: + if not glob.glob(database_path + "_*"): + logging.error( + "Could not find HHsearch database %s", database_path + ) + raise ValueError( + f"Could not find HHsearch database {database_path}" + ) + + def query(self, a3m: str) -> str: + """Queries the database using HHsearch using a given a3m.""" + with utils.tmpdir_manager(base_dir="/tmp") as query_tmp_dir: + input_path = os.path.join(query_tmp_dir, "query.a3m") + hhr_path = os.path.join(query_tmp_dir, "output.hhr") + with open(input_path, "w") as f: + f.write(a3m) + + db_cmd = [] + for db_path in self.databases: + db_cmd.append("-d") + db_cmd.append(db_path) + cmd = [ + self.binary_path, + "-i", + input_path, + "-o", + hhr_path, + "-maxseq", + str(self.maxseq), + "-cpu", + str(self.n_cpu), + ] + db_cmd + + logging.info('Launching subprocess "%s"', " ".join(cmd)) + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + with utils.timing("HHsearch query"): + stdout, stderr = process.communicate() + retcode = process.wait() + + if retcode: + # Stderr is truncated to prevent proto size errors in Beam. + raise RuntimeError( + "HHSearch failed:\nstdout:\n%s\n\nstderr:\n%s\n" + % (stdout.decode("utf-8"), stderr[:100_000].decode("utf-8")) + ) + + with open(hhr_path) as f: + hhr = f.read() + return hhr diff --git a/gafl/openfold/data/tools/jackhmmer.py b/gafl/openfold/data/tools/jackhmmer.py new file mode 100644 index 0000000000000000000000000000000000000000..fca93edfe08fee383e40c451a647d8ff48230f3c --- /dev/null +++ b/gafl/openfold/data/tools/jackhmmer.py @@ -0,0 +1,228 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Library to run Jackhmmer from Python.""" + +from concurrent import futures +import glob +import logging +import os +import subprocess +from typing import Any, Callable, Mapping, Optional, Sequence +from urllib import request + +from openfold.data.tools import utils + + +class Jackhmmer: + """Python wrapper of the Jackhmmer binary.""" + + def __init__( + self, + *, + binary_path: str, + database_path: str, + n_cpu: int = 8, + n_iter: int = 1, + e_value: float = 0.0001, + z_value: Optional[int] = None, + get_tblout: bool = False, + filter_f1: float = 0.0005, + filter_f2: float = 0.00005, + filter_f3: float = 0.0000005, + incdom_e: Optional[float] = None, + dom_e: Optional[float] = None, + num_streamed_chunks: Optional[int] = None, + streaming_callback: Optional[Callable[[int], None]] = None, + ): + """Initializes the Python Jackhmmer wrapper. + + Args: + binary_path: The path to the jackhmmer executable. + database_path: The path to the jackhmmer database (FASTA format). + n_cpu: The number of CPUs to give Jackhmmer. + n_iter: The number of Jackhmmer iterations. + e_value: The E-value, see Jackhmmer docs for more details. + z_value: The Z-value, see Jackhmmer docs for more details. + get_tblout: Whether to save tblout string. + filter_f1: MSV and biased composition pre-filter, set to >1.0 to turn off. + filter_f2: Viterbi pre-filter, set to >1.0 to turn off. + filter_f3: Forward pre-filter, set to >1.0 to turn off. + incdom_e: Domain e-value criteria for inclusion of domains in MSA/next + round. + dom_e: Domain e-value criteria for inclusion in tblout. + num_streamed_chunks: Number of database chunks to stream over. + streaming_callback: Callback function run after each chunk iteration with + the iteration number as argument. + """ + self.binary_path = binary_path + self.database_path = database_path + self.num_streamed_chunks = num_streamed_chunks + + if ( + not os.path.exists(self.database_path) + and num_streamed_chunks is None + ): + logging.error("Could not find Jackhmmer database %s", database_path) + raise ValueError( + f"Could not find Jackhmmer database {database_path}" + ) + + self.n_cpu = n_cpu + self.n_iter = n_iter + self.e_value = e_value + self.z_value = z_value + self.filter_f1 = filter_f1 + self.filter_f2 = filter_f2 + self.filter_f3 = filter_f3 + self.incdom_e = incdom_e + self.dom_e = dom_e + self.get_tblout = get_tblout + self.streaming_callback = streaming_callback + + def _query_chunk( + self, input_fasta_path: str, database_path: str + ) -> Mapping[str, Any]: + """Queries the database chunk using Jackhmmer.""" + with utils.tmpdir_manager(base_dir="/tmp") as query_tmp_dir: + sto_path = os.path.join(query_tmp_dir, "output.sto") + + # The F1/F2/F3 are the expected proportion to pass each of the filtering + # stages (which get progressively more expensive), reducing these + # speeds up the pipeline at the expensive of sensitivity. They are + # currently set very low to make querying Mgnify run in a reasonable + # amount of time. + cmd_flags = [ + # Don't pollute stdout with Jackhmmer output. + "-o", + "/dev/null", + "-A", + sto_path, + "--noali", + "--F1", + str(self.filter_f1), + "--F2", + str(self.filter_f2), + "--F3", + str(self.filter_f3), + "--incE", + str(self.e_value), + # Report only sequences with E-values <= x in per-sequence output. + "-E", + str(self.e_value), + "--cpu", + str(self.n_cpu), + "-N", + str(self.n_iter), + ] + if self.get_tblout: + tblout_path = os.path.join(query_tmp_dir, "tblout.txt") + cmd_flags.extend(["--tblout", tblout_path]) + + if self.z_value: + cmd_flags.extend(["-Z", str(self.z_value)]) + + if self.dom_e is not None: + cmd_flags.extend(["--domE", str(self.dom_e)]) + + if self.incdom_e is not None: + cmd_flags.extend(["--incdomE", str(self.incdom_e)]) + + cmd = ( + [self.binary_path] + + cmd_flags + + [input_fasta_path, database_path] + ) + + logging.info('Launching subprocess "%s"', " ".join(cmd)) + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + with utils.timing( + f"Jackhmmer ({os.path.basename(database_path)}) query" + ): + _, stderr = process.communicate() + retcode = process.wait() + + if retcode: + raise RuntimeError( + "Jackhmmer failed\nstderr:\n%s\n" % stderr.decode("utf-8") + ) + + # Get e-values for each target name + tbl = "" + if self.get_tblout: + with open(tblout_path) as f: + tbl = f.read() + + with open(sto_path) as f: + sto = f.read() + + raw_output = dict( + sto=sto, + tbl=tbl, + stderr=stderr, + n_iter=self.n_iter, + e_value=self.e_value, + ) + + return raw_output + + def query(self, input_fasta_path: str) -> Sequence[Mapping[str, Any]]: + """Queries the database using Jackhmmer.""" + if self.num_streamed_chunks is None: + return [self._query_chunk(input_fasta_path, self.database_path)] + + db_basename = os.path.basename(self.database_path) + db_remote_chunk = lambda db_idx: f"{self.database_path}.{db_idx}" + db_local_chunk = lambda db_idx: f"/tmp/ramdisk/{db_basename}.{db_idx}" + + # Remove existing files to prevent OOM + for f in glob.glob(db_local_chunk("[0-9]*")): + try: + os.remove(f) + except OSError: + print(f"OSError while deleting {f}") + + # Download the (i+1)-th chunk while Jackhmmer is running on the i-th chunk + with futures.ThreadPoolExecutor(max_workers=2) as executor: + chunked_output = [] + for i in range(1, self.num_streamed_chunks + 1): + # Copy the chunk locally + if i == 1: + future = executor.submit( + request.urlretrieve, + db_remote_chunk(i), + db_local_chunk(i), + ) + if i < self.num_streamed_chunks: + next_future = executor.submit( + request.urlretrieve, + db_remote_chunk(i + 1), + db_local_chunk(i + 1), + ) + + # Run Jackhmmer with the chunk + future.result() + chunked_output.append( + self._query_chunk(input_fasta_path, db_local_chunk(i)) + ) + + # Remove the local copy of the chunk + os.remove(db_local_chunk(i)) + future = next_future + if self.streaming_callback: + self.streaming_callback(i) + return chunked_output diff --git a/gafl/openfold/data/tools/kalign.py b/gafl/openfold/data/tools/kalign.py new file mode 100644 index 0000000000000000000000000000000000000000..5306f864bc220dbd979fd1ae556df56c3e65ff71 --- /dev/null +++ b/gafl/openfold/data/tools/kalign.py @@ -0,0 +1,115 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""A Python wrapper for Kalign.""" +import os +import subprocess +from typing import Sequence + +from absl import logging + +from openfold.data.tools import utils + + +def _to_a3m(sequences: Sequence[str]) -> str: + """Converts sequences to an a3m file.""" + names = ["sequence %d" % i for i in range(1, len(sequences) + 1)] + a3m = [] + for sequence, name in zip(sequences, names): + a3m.append(u">" + name + u"\n") + a3m.append(sequence + u"\n") + return "".join(a3m) + + +class Kalign: + """Python wrapper of the Kalign binary.""" + + def __init__(self, *, binary_path: str): + """Initializes the Python Kalign wrapper. + + Args: + binary_path: The path to the Kalign binary. + + Raises: + RuntimeError: If Kalign binary not found within the path. + """ + self.binary_path = binary_path + + def align(self, sequences: Sequence[str]) -> str: + """Aligns the sequences and returns the alignment in A3M string. + + Args: + sequences: A list of query sequence strings. The sequences have to be at + least 6 residues long (Kalign requires this). Note that the order in + which you give the sequences might alter the output slightly as + different alignment tree might get constructed. + + Returns: + A string with the alignment in a3m format. + + Raises: + RuntimeError: If Kalign fails. + ValueError: If any of the sequences is less than 6 residues long. + """ + logging.info("Aligning %d sequences", len(sequences)) + + for s in sequences: + if len(s) < 6: + raise ValueError( + "Kalign requires all sequences to be at least 6 " + "residues long. Got %s (%d residues)." % (s, len(s)) + ) + + with utils.tmpdir_manager(base_dir="/tmp") as query_tmp_dir: + input_fasta_path = os.path.join(query_tmp_dir, "input.fasta") + output_a3m_path = os.path.join(query_tmp_dir, "output.a3m") + + with open(input_fasta_path, "w") as f: + f.write(_to_a3m(sequences)) + + cmd = [ + self.binary_path, + "-i", + input_fasta_path, + "-o", + output_a3m_path, + "-format", + "fasta", + ] + + logging.info('Launching subprocess "%s"', " ".join(cmd)) + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + + with utils.timing("Kalign query"): + stdout, stderr = process.communicate() + retcode = process.wait() + logging.info( + "Kalign stdout:\n%s\n\nstderr:\n%s\n", + stdout.decode("utf-8"), + stderr.decode("utf-8"), + ) + + if retcode: + raise RuntimeError( + "Kalign failed\nstdout:\n%s\n\nstderr:\n%s\n" + % (stdout.decode("utf-8"), stderr.decode("utf-8")) + ) + + with open(output_a3m_path) as f: + a3m = f.read() + + return a3m diff --git a/gafl/openfold/data/tools/utils.py b/gafl/openfold/data/tools/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e8684f1e3e6f20f9098c16009836ac737106c2 --- /dev/null +++ b/gafl/openfold/data/tools/utils.py @@ -0,0 +1,48 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common utilities for data pipeline tools.""" +import contextlib +import datetime +import logging +import shutil +import tempfile +import time +from typing import Optional + + +@contextlib.contextmanager +def tmpdir_manager(base_dir: Optional[str] = None): + """Context manager that deletes a temporary directory on exit.""" + tmpdir = tempfile.mkdtemp(dir=base_dir) + try: + yield tmpdir + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +@contextlib.contextmanager +def timing(msg: str): + logging.info("Started %s", msg) + tic = time.perf_counter() + yield + toc = time.perf_counter() + logging.info("Finished %s in %.3f seconds", msg, toc - tic) + + +def to_date(s: str): + return datetime.datetime( + year=int(s[:4]), month=int(s[5:7]), day=int(s[8:10]) + ) diff --git a/gafl/openfold/model/__init__.py b/gafl/openfold/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25d1a5ba4be7300076d6f44af1541a33ca9e4ab1 --- /dev/null +++ b/gafl/openfold/model/__init__.py @@ -0,0 +1,16 @@ +import os +import glob +import importlib as importlib + +_files = glob.glob(os.path.join(os.path.dirname(__file__), "*.py")) +__all__ = [ + os.path.basename(f)[:-3] + for f in _files + if os.path.isfile(f) and not f.endswith("__init__.py") +] +_modules = [(m, importlib.import_module("." + m, __name__)) for m in __all__] +for _m in _modules: + globals()[_m[0]] = _m[1] + +# Avoid needlessly cluttering the global namespace +del _files, _m, _modules diff --git a/gafl/openfold/model/dropout.py b/gafl/openfold/model/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..651b9775ef44fba20dec75c60703f00beac66e0c --- /dev/null +++ b/gafl/openfold/model/dropout.py @@ -0,0 +1,78 @@ +# Copyright 2021 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch +import torch.nn as nn +from functools import partialmethod +from typing import Union, List + + +class Dropout(nn.Module): + """ + Implementation of dropout with the ability to share the dropout mask + along a particular dimension. + + If not in training mode, this module computes the identity function. + """ + + def __init__(self, r: float, batch_dim: Union[int, List[int]]): + """ + Args: + r: + Dropout rate + batch_dim: + Dimension(s) along which the dropout mask is shared + """ + super(Dropout, self).__init__() + + self.r = r + if type(batch_dim) == int: + batch_dim = [batch_dim] + self.batch_dim = batch_dim + self.dropout = nn.Dropout(self.r) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: + Tensor to which dropout is applied. Can have any shape + compatible with self.batch_dim + """ + shape = list(x.shape) + if self.batch_dim is not None: + for bd in self.batch_dim: + shape[bd] = 1 + mask = x.new_ones(shape) + mask = self.dropout(mask) + x *= mask + return x + + +class DropoutRowwise(Dropout): + """ + Convenience class for rowwise dropout as described in subsection + 1.11.6. + """ + + __init__ = partialmethod(Dropout.__init__, batch_dim=-3) + + +class DropoutColumnwise(Dropout): + """ + Convenience class for columnwise dropout as described in subsection + 1.11.6. + """ + + __init__ = partialmethod(Dropout.__init__, batch_dim=-2) diff --git a/gafl/openfold/model/embedders.py b/gafl/openfold/model/embedders.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f1f9981c9965be630fd1ccb98ebdcf0fe42dc5 --- /dev/null +++ b/gafl/openfold/model/embedders.py @@ -0,0 +1,352 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn +from typing import Tuple + +from openfold.model.primitives import Linear, LayerNorm +from openfold.utils.tensor_utils import one_hot + + +class InputEmbedder(nn.Module): + """ + Embeds a subset of the input features. + + Implements Algorithms 3 (InputEmbedder) and 4 (relpos). + """ + + def __init__( + self, + tf_dim: int, + msa_dim: int, + c_z: int, + c_m: int, + relpos_k: int, + **kwargs, + ): + """ + Args: + tf_dim: + Final dimension of the target features + msa_dim: + Final dimension of the MSA features + c_z: + Pair embedding dimension + c_m: + MSA embedding dimension + relpos_k: + Window size used in relative positional encoding + """ + super(InputEmbedder, self).__init__() + + self.tf_dim = tf_dim + self.msa_dim = msa_dim + + self.c_z = c_z + self.c_m = c_m + + self.linear_tf_z_i = Linear(tf_dim, c_z) + self.linear_tf_z_j = Linear(tf_dim, c_z) + self.linear_tf_m = Linear(tf_dim, c_m) + self.linear_msa_m = Linear(msa_dim, c_m) + + # RPE stuff + self.relpos_k = relpos_k + self.no_bins = 2 * relpos_k + 1 + self.linear_relpos = Linear(self.no_bins, c_z) + + def relpos(self, ri: torch.Tensor): + """ + Computes relative positional encodings + + Implements Algorithm 4. + + Args: + ri: + "residue_index" features of shape [*, N] + """ + d = ri[..., None] - ri[..., None, :] + boundaries = torch.arange( + start=-self.relpos_k, end=self.relpos_k + 1, device=d.device + ) + oh = one_hot(d, boundaries).type(ri.dtype) + return self.linear_relpos(oh) + + def forward( + self, + tf: torch.Tensor, + ri: torch.Tensor, + msa: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + tf: + "target_feat" features of shape [*, N_res, tf_dim] + ri: + "residue_index" features of shape [*, N_res] + msa: + "msa_feat" features of shape [*, N_clust, N_res, msa_dim] + Returns: + msa_emb: + [*, N_clust, N_res, C_m] MSA embedding + pair_emb: + [*, N_res, N_res, C_z] pair embedding + + """ + # [*, N_res, c_z] + tf_emb_i = self.linear_tf_z_i(tf) + tf_emb_j = self.linear_tf_z_j(tf) + + # [*, N_res, N_res, c_z] + pair_emb = tf_emb_i[..., None, :] + tf_emb_j[..., None, :, :] + pair_emb = pair_emb + self.relpos(ri.type(pair_emb.dtype)) + + # [*, N_clust, N_res, c_m] + n_clust = msa.shape[-3] + tf_m = ( + self.linear_tf_m(tf) + .unsqueeze(-3) + .expand(((-1,) * len(tf.shape[:-2]) + (n_clust, -1, -1))) + ) + msa_emb = self.linear_msa_m(msa) + tf_m + + return msa_emb, pair_emb + + +class RecyclingEmbedder(nn.Module): + """ + Embeds the output of an iteration of the model for recycling. + + Implements Algorithm 32. + """ + + def __init__( + self, + c_m: int, + c_z: int, + min_bin: float, + max_bin: float, + no_bins: int, + inf: float = 1e8, + **kwargs, + ): + """ + Args: + c_m: + MSA channel dimension + c_z: + Pair embedding channel dimension + min_bin: + Smallest distogram bin (Angstroms) + max_bin: + Largest distogram bin (Angstroms) + no_bins: + Number of distogram bins + """ + super(RecyclingEmbedder, self).__init__() + + self.c_m = c_m + self.c_z = c_z + self.min_bin = min_bin + self.max_bin = max_bin + self.no_bins = no_bins + self.inf = inf + + self.bins = None + + self.linear = Linear(self.no_bins, self.c_z) + self.layer_norm_m = LayerNorm(self.c_m) + self.layer_norm_z = LayerNorm(self.c_z) + + def forward( + self, + m: torch.Tensor, + z: torch.Tensor, + x: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + m: + First row of the MSA embedding. [*, N_res, C_m] + z: + [*, N_res, N_res, C_z] pair embedding + x: + [*, N_res, 3] predicted C_beta coordinates + Returns: + m: + [*, N_res, C_m] MSA embedding update + z: + [*, N_res, N_res, C_z] pair embedding update + """ + if self.bins is None: + self.bins = torch.linspace( + self.min_bin, + self.max_bin, + self.no_bins, + dtype=x.dtype, + device=x.device, + requires_grad=False, + ) + + # [*, N, C_m] + m_update = self.layer_norm_m(m) + + # This squared method might become problematic in FP16 mode. + # I'm using it because my homegrown method had a stubborn discrepancy I + # couldn't find in time. + squared_bins = self.bins ** 2 + upper = torch.cat( + [squared_bins[1:], squared_bins.new_tensor([self.inf])], dim=-1 + ) + d = torch.sum( + (x[..., None, :] - x[..., None, :, :]) ** 2, dim=-1, keepdims=True + ) + + # [*, N, N, no_bins] + d = ((d > squared_bins) * (d < upper)).type(x.dtype) + + # [*, N, N, C_z] + d = self.linear(d) + z_update = d + self.layer_norm_z(z) + + return m_update, z_update + + +class TemplateAngleEmbedder(nn.Module): + """ + Embeds the "template_angle_feat" feature. + + Implements Algorithm 2, line 7. + """ + + def __init__( + self, + c_in: int, + c_out: int, + **kwargs, + ): + """ + Args: + c_in: + Final dimension of "template_angle_feat" + c_out: + Output channel dimension + """ + super(TemplateAngleEmbedder, self).__init__() + + self.c_out = c_out + self.c_in = c_in + + self.linear_1 = Linear(self.c_in, self.c_out, init="relu") + self.relu = nn.ReLU() + self.linear_2 = Linear(self.c_out, self.c_out, init="relu") + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: [*, N_templ, N_res, c_in] "template_angle_feat" features + Returns: + x: [*, N_templ, N_res, C_out] embedding + """ + x = self.linear_1(x) + x = self.relu(x) + x = self.linear_2(x) + + return x + + +class TemplatePairEmbedder(nn.Module): + """ + Embeds "template_pair_feat" features. + + Implements Algorithm 2, line 9. + """ + + def __init__( + self, + c_in: int, + c_out: int, + **kwargs, + ): + """ + Args: + c_in: + + c_out: + Output channel dimension + """ + super(TemplatePairEmbedder, self).__init__() + + self.c_in = c_in + self.c_out = c_out + + # Despite there being no relu nearby, the source uses that initializer + self.linear = Linear(self.c_in, self.c_out, init="relu") + + def forward( + self, + x: torch.Tensor, + ) -> torch.Tensor: + """ + Args: + x: + [*, C_in] input tensor + Returns: + [*, C_out] output tensor + """ + x = self.linear(x) + + return x + + +class ExtraMSAEmbedder(nn.Module): + """ + Embeds unclustered MSA sequences. + + Implements Algorithm 2, line 15 + """ + + def __init__( + self, + c_in: int, + c_out: int, + **kwargs, + ): + """ + Args: + c_in: + Input channel dimension + c_out: + Output channel dimension + """ + super(ExtraMSAEmbedder, self).__init__() + + self.c_in = c_in + self.c_out = c_out + + self.linear = Linear(self.c_in, self.c_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: + [*, N_extra_seq, N_res, C_in] "extra_msa_feat" features + Returns: + [*, N_extra_seq, N_res, C_out] embedding + """ + x = self.linear(x) + + return x diff --git a/gafl/openfold/model/evoformer.py b/gafl/openfold/model/evoformer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a862097a40dcb81514e3522494a66ea5078b01 --- /dev/null +++ b/gafl/openfold/model/evoformer.py @@ -0,0 +1,630 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import torch +import torch.nn as nn +from typing import Tuple, Optional +from functools import partial + +from openfold.model.primitives import Linear, LayerNorm +from openfold.model.dropout import DropoutRowwise, DropoutColumnwise +from openfold.model.msa import ( + MSARowAttentionWithPairBias, + MSAColumnAttention, + MSAColumnGlobalAttention, +) +from openfold.model.outer_product_mean import OuterProductMean +from openfold.model.pair_transition import PairTransition +from openfold.model.triangular_attention import ( + TriangleAttentionStartingNode, + TriangleAttentionEndingNode, +) +from openfold.model.triangular_multiplicative_update import ( + TriangleMultiplicationOutgoing, + TriangleMultiplicationIncoming, +) +from openfold.utils.checkpointing import checkpoint_blocks, get_checkpoint_fn +from openfold.utils.tensor_utils import chunk_layer + + +class MSATransition(nn.Module): + """ + Feed-forward network applied to MSA activations after attention. + + Implements Algorithm 9 + """ + def __init__(self, c_m, n): + """ + Args: + c_m: + MSA channel dimension + n: + Factor multiplied to c_m to obtain the hidden channel + dimension + """ + super(MSATransition, self).__init__() + + self.c_m = c_m + self.n = n + + self.layer_norm = LayerNorm(self.c_m) + self.linear_1 = Linear(self.c_m, self.n * self.c_m, init="relu") + self.relu = nn.ReLU() + self.linear_2 = Linear(self.n * self.c_m, self.c_m, init="final") + + def _transition(self, m, mask): + m = self.linear_1(m) + m = self.relu(m) + m = self.linear_2(m) * mask + return m + + @torch.jit.ignore + def _chunk(self, + m: torch.Tensor, + mask: torch.Tensor, + chunk_size: int, + ) -> torch.Tensor: + return chunk_layer( + self._transition, + {"m": m, "mask": mask}, + chunk_size=chunk_size, + no_batch_dims=len(m.shape[:-2]), + ) + + + def forward( + self, + m: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None, + ) -> torch.Tensor: + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA activation + mask: + [*, N_seq, N_res, C_m] MSA mask + Returns: + m: + [*, N_seq, N_res, C_m] MSA activation update + """ + # DISCREPANCY: DeepMind forgets to apply the MSA mask here. + if mask is None: + mask = m.new_ones(m.shape[:-1]) + + mask = mask.unsqueeze(-1) + + m = self.layer_norm(m) + + if chunk_size is not None: + m = self._chunk(m, mask, chunk_size) + else: + m = self._transition(m, mask) + + return m + + +class EvoformerBlockCore(nn.Module): + def __init__( + self, + c_m: int, + c_z: int, + c_hidden_opm: int, + c_hidden_mul: int, + c_hidden_pair_att: int, + no_heads_msa: int, + no_heads_pair: int, + transition_n: int, + pair_dropout: float, + inf: float, + eps: float, + _is_extra_msa_stack: bool = False, + ): + super(EvoformerBlockCore, self).__init__() + + self.msa_transition = MSATransition( + c_m=c_m, + n=transition_n, + ) + + self.outer_product_mean = OuterProductMean( + c_m, + c_z, + c_hidden_opm, + ) + + self.tri_mul_out = TriangleMultiplicationOutgoing( + c_z, + c_hidden_mul, + ) + self.tri_mul_in = TriangleMultiplicationIncoming( + c_z, + c_hidden_mul, + ) + + self.tri_att_start = TriangleAttentionStartingNode( + c_z, + c_hidden_pair_att, + no_heads_pair, + inf=inf, + ) + self.tri_att_end = TriangleAttentionEndingNode( + c_z, + c_hidden_pair_att, + no_heads_pair, + inf=inf, + ) + + self.pair_transition = PairTransition( + c_z, + transition_n, + ) + + self.ps_dropout_row_layer = DropoutRowwise(pair_dropout) + self.ps_dropout_col_layer = DropoutColumnwise(pair_dropout) + + def forward( + self, + m: torch.Tensor, + z: torch.Tensor, + msa_mask: torch.Tensor, + pair_mask: torch.Tensor, + chunk_size: Optional[int] = None, + _mask_trans: bool = True, + ) -> Tuple[torch.Tensor, torch.Tensor]: + # DeepMind doesn't mask these transitions in the source, so _mask_trans + # should be disabled to better approximate the exact activations of + # the original. + msa_trans_mask = msa_mask if _mask_trans else None + pair_trans_mask = pair_mask if _mask_trans else None + + m = m + self.msa_transition( + m, mask=msa_trans_mask, chunk_size=chunk_size + ) + z = z + self.outer_product_mean( + m, mask=msa_mask, chunk_size=chunk_size + ) + z = z + self.ps_dropout_row_layer(self.tri_mul_out(z, mask=pair_mask)) + z = z + self.ps_dropout_row_layer(self.tri_mul_in(z, mask=pair_mask)) + z = z + self.ps_dropout_row_layer( + self.tri_att_start(z, mask=pair_mask, chunk_size=chunk_size) + ) + z = z + self.ps_dropout_col_layer( + self.tri_att_end(z, mask=pair_mask, chunk_size=chunk_size) + ) + z = z + self.pair_transition( + z, mask=pair_trans_mask, chunk_size=chunk_size + ) + + return m, z + + +class EvoformerBlock(nn.Module): + def __init__(self, + c_m: int, + c_z: int, + c_hidden_msa_att: int, + c_hidden_opm: int, + c_hidden_mul: int, + c_hidden_pair_att: int, + no_heads_msa: int, + no_heads_pair: int, + transition_n: int, + msa_dropout: float, + pair_dropout: float, + inf: float, + eps: float, + ): + super(EvoformerBlock, self).__init__() + + self.msa_att_row = MSARowAttentionWithPairBias( + c_m=c_m, + c_z=c_z, + c_hidden=c_hidden_msa_att, + no_heads=no_heads_msa, + inf=inf, + ) + + self.msa_att_col = MSAColumnAttention( + c_m, + c_hidden_msa_att, + no_heads_msa, + inf=inf, + ) + + self.msa_dropout_layer = DropoutRowwise(msa_dropout) + + self.core = EvoformerBlockCore( + c_m=c_m, + c_z=c_z, + c_hidden_opm=c_hidden_opm, + c_hidden_mul=c_hidden_mul, + c_hidden_pair_att=c_hidden_pair_att, + no_heads_msa=no_heads_msa, + no_heads_pair=no_heads_pair, + transition_n=transition_n, + pair_dropout=pair_dropout, + inf=inf, + eps=eps, + ) + + def forward(self, + m: torch.Tensor, + z: torch.Tensor, + msa_mask: torch.Tensor, + pair_mask: torch.Tensor, + chunk_size: Optional[int] = None, + _mask_trans: bool = True, + ) -> Tuple[torch.Tensor, torch.Tensor]: + m = m + self.msa_dropout_layer( + self.msa_att_row(m, z=z, mask=msa_mask, chunk_size=chunk_size) + ) + m = m + self.msa_att_col(m, mask=msa_mask, chunk_size=chunk_size) + m, z = self.core( + m, + z, + msa_mask=msa_mask, + pair_mask=pair_mask, + chunk_size=chunk_size, + _mask_trans=_mask_trans, + ) + + return m, z + + +class ExtraMSABlock(nn.Module): + """ + Almost identical to the standard EvoformerBlock, except in that the + ExtraMSABlock uses GlobalAttention for MSA column attention and + requires more fine-grained control over checkpointing. Separated from + its twin to preserve the TorchScript-ability of the latter. + """ + def __init__(self, + c_m: int, + c_z: int, + c_hidden_msa_att: int, + c_hidden_opm: int, + c_hidden_mul: int, + c_hidden_pair_att: int, + no_heads_msa: int, + no_heads_pair: int, + transition_n: int, + msa_dropout: float, + pair_dropout: float, + inf: float, + eps: float, + ckpt: bool, + ): + super(ExtraMSABlock, self).__init__() + + self.ckpt = ckpt + + self.msa_att_row = MSARowAttentionWithPairBias( + c_m=c_m, + c_z=c_z, + c_hidden=c_hidden_msa_att, + no_heads=no_heads_msa, + inf=inf, + ) + + self.msa_att_col = MSAColumnGlobalAttention( + c_in=c_m, + c_hidden=c_hidden_msa_att, + no_heads=no_heads_msa, + inf=inf, + eps=eps, + ) + + self.msa_dropout_layer = DropoutRowwise(msa_dropout) + + self.core = EvoformerBlockCore( + c_m=c_m, + c_z=c_z, + c_hidden_opm=c_hidden_opm, + c_hidden_mul=c_hidden_mul, + c_hidden_pair_att=c_hidden_pair_att, + no_heads_msa=no_heads_msa, + no_heads_pair=no_heads_pair, + transition_n=transition_n, + pair_dropout=pair_dropout, + inf=inf, + eps=eps, + ) + + def forward(self, + m: torch.Tensor, + z: torch.Tensor, + msa_mask: torch.Tensor, + pair_mask: torch.Tensor, + chunk_size: Optional[int] = None, + _chunk_logits: Optional[int] = 1024, + ) -> Tuple[torch.Tensor, torch.Tensor]: + def add(m1, m2): + # The first operation in a checkpoint can't be in-place, but it's + # nice to have in-place addition during inference. Thus... + if(torch.is_grad_enabled()): + m1 = m1 + m2 + else: + m1 += m2 + + return m1 + + m = add(m, self.msa_dropout_layer( + self.msa_att_row( + m.clone() if torch.is_grad_enabled() else m, + z=z.clone() if torch.is_grad_enabled() else z, + mask=msa_mask, + chunk_size=chunk_size, + _chunk_logits=_chunk_logits if torch.is_grad_enabled() else None, + _checkpoint_chunks= + self.ckpt if torch.is_grad_enabled() else False, + ) + )) + + def fn(m, z): + m = add(m, self.msa_att_col(m, mask=msa_mask, chunk_size=chunk_size)) + m, z = self.core( + m, z, msa_mask=msa_mask, pair_mask=pair_mask, chunk_size=chunk_size + ) + + return m, z + + if(torch.is_grad_enabled() and self.ckpt): + checkpoint_fn = get_checkpoint_fn() + m, z = checkpoint_fn(fn, m, z) + else: + m, z = fn(m, z) + + return m, z + + +class EvoformerStack(nn.Module): + """ + Main Evoformer trunk. + + Implements Algorithm 6. + """ + + def __init__( + self, + c_m: int, + c_z: int, + c_hidden_msa_att: int, + c_hidden_opm: int, + c_hidden_mul: int, + c_hidden_pair_att: int, + c_s: int, + no_heads_msa: int, + no_heads_pair: int, + no_blocks: int, + transition_n: int, + msa_dropout: float, + pair_dropout: float, + blocks_per_ckpt: int, + inf: float, + eps: float, + clear_cache_between_blocks: bool = False, + **kwargs, + ): + """ + Args: + c_m: + MSA channel dimension + c_z: + Pair channel dimension + c_hidden_msa_att: + Hidden dimension in MSA attention + c_hidden_opm: + Hidden dimension in outer product mean module + c_hidden_mul: + Hidden dimension in multiplicative updates + c_hidden_pair_att: + Hidden dimension in triangular attention + c_s: + Channel dimension of the output "single" embedding + no_heads_msa: + Number of heads used for MSA attention + no_heads_pair: + Number of heads used for pair attention + no_blocks: + Number of Evoformer blocks in the stack + transition_n: + Factor by which to multiply c_m to obtain the MSATransition + hidden dimension + msa_dropout: + Dropout rate for MSA activations + pair_dropout: + Dropout used for pair activations + blocks_per_ckpt: + Number of Evoformer blocks in each activation checkpoint + clear_cache_between_blocks: + Whether to clear CUDA's GPU memory cache between blocks of the + stack. Slows down each block but can reduce fragmentation + """ + super(EvoformerStack, self).__init__() + + self.blocks_per_ckpt = blocks_per_ckpt + self.clear_cache_between_blocks = clear_cache_between_blocks + + self.blocks = nn.ModuleList() + + for _ in range(no_blocks): + block = EvoformerBlock( + c_m=c_m, + c_z=c_z, + c_hidden_msa_att=c_hidden_msa_att, + c_hidden_opm=c_hidden_opm, + c_hidden_mul=c_hidden_mul, + c_hidden_pair_att=c_hidden_pair_att, + no_heads_msa=no_heads_msa, + no_heads_pair=no_heads_pair, + transition_n=transition_n, + msa_dropout=msa_dropout, + pair_dropout=pair_dropout, + inf=inf, + eps=eps, + ) + self.blocks.append(block) + + self.linear = Linear(c_m, c_s) + + def forward(self, + m: torch.Tensor, + z: torch.Tensor, + msa_mask: torch.Tensor, + pair_mask: torch.Tensor, + chunk_size: int, + _mask_trans: bool = True, + ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA embedding + z: + [*, N_res, N_res, C_z] pair embedding + msa_mask: + [*, N_seq, N_res] MSA mask + pair_mask: + [*, N_res, N_res] pair mask + Returns: + m: + [*, N_seq, N_res, C_m] MSA embedding + z: + [*, N_res, N_res, C_z] pair embedding + s: + [*, N_res, C_s] single embedding (or None if extra MSA stack) + """ + blocks = [ + partial( + b, + msa_mask=msa_mask, + pair_mask=pair_mask, + chunk_size=chunk_size, + _mask_trans=_mask_trans, + ) + for b in self.blocks + ] + + if(self.clear_cache_between_blocks): + def block_with_cache_clear(block, *args): + torch.cuda.empty_cache() + return block(*args) + + blocks = [partial(block_with_cache_clear, b) for b in blocks] + + m, z = checkpoint_blocks( + blocks, + args=(m, z), + blocks_per_ckpt=self.blocks_per_ckpt if self.training else None, + ) + + s = self.linear(m[..., 0, :, :]) + + return m, z, s + + +class ExtraMSAStack(nn.Module): + """ + Implements Algorithm 18. + """ + + def __init__(self, + c_m: int, + c_z: int, + c_hidden_msa_att: int, + c_hidden_opm: int, + c_hidden_mul: int, + c_hidden_pair_att: int, + no_heads_msa: int, + no_heads_pair: int, + no_blocks: int, + transition_n: int, + msa_dropout: float, + pair_dropout: float, + inf: float, + eps: float, + ckpt: bool, + clear_cache_between_blocks: bool = False, + **kwargs, + ): + super(ExtraMSAStack, self).__init__() + + self.clear_cache_between_blocks = clear_cache_between_blocks + self.blocks = nn.ModuleList() + for _ in range(no_blocks): + block = ExtraMSABlock( + c_m=c_m, + c_z=c_z, + c_hidden_msa_att=c_hidden_msa_att, + c_hidden_opm=c_hidden_opm, + c_hidden_mul=c_hidden_mul, + c_hidden_pair_att=c_hidden_pair_att, + no_heads_msa=no_heads_msa, + no_heads_pair=no_heads_pair, + transition_n=transition_n, + msa_dropout=msa_dropout, + pair_dropout=pair_dropout, + inf=inf, + eps=eps, + ckpt=ckpt, + ) + self.blocks.append(block) + + def forward(self, + m: torch.Tensor, + z: torch.Tensor, + chunk_size: int, + msa_mask: Optional[torch.Tensor] = None, + pair_mask: Optional[torch.Tensor] = None, + _mask_trans: bool = True, + ) -> torch.Tensor: + """ + Args: + m: + [*, N_extra, N_res, C_m] extra MSA embedding + z: + [*, N_res, N_res, C_z] pair embedding + msa_mask: + Optional [*, N_extra, N_res] MSA mask + pair_mask: + Optional [*, N_res, N_res] pair mask + Returns: + [*, N_res, N_res, C_z] pair update + """ + #checkpoint_fn = get_checkpoint_fn() + #blocks = [ + # partial(b, msa_mask=msa_mask, pair_mask=pair_mask, chunk_size=chunk_size, _chunk_logits=None) for b in self.blocks + #] + + #def dodo(b, *args): + # torch.cuda.empty_cache() + # return b(*args) + + #blocks = [partial(dodo, b) for b in blocks] + + #for b in blocks: + # if(torch.is_grad_enabled()): + # m, z = checkpoint_fn(b, *(m, z)) + # else: + # m, z = b(m, z) + + for b in self.blocks: + m, z = b(m, z, msa_mask, pair_mask, chunk_size=chunk_size) + + if(self.clear_cache_between_blocks): + torch.cuda.empty_cache() + + return z diff --git a/gafl/openfold/model/heads.py b/gafl/openfold/model/heads.py new file mode 100644 index 0000000000000000000000000000000000000000..f46126d741e79d177a80220f89e1523a408e569b --- /dev/null +++ b/gafl/openfold/model/heads.py @@ -0,0 +1,251 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear, LayerNorm +from openfold.utils.loss import ( + compute_plddt, + compute_tm, + compute_predicted_aligned_error, +) + + +class AuxiliaryHeads(nn.Module): + def __init__(self, config): + super(AuxiliaryHeads, self).__init__() + + self.plddt = PerResidueLDDTCaPredictor( + **config["lddt"], + ) + + self.distogram = DistogramHead( + **config["distogram"], + ) + + self.masked_msa = MaskedMSAHead( + **config["masked_msa"], + ) + + self.experimentally_resolved = ExperimentallyResolvedHead( + **config["experimentally_resolved"], + ) + + if config.tm.enabled: + self.tm = TMScoreHead( + **config.tm, + ) + + self.config = config + + def forward(self, outputs): + aux_out = {} + lddt_logits = self.plddt(outputs["sm"]["single"]) + aux_out["lddt_logits"] = lddt_logits + + # Required for relaxation later on + aux_out["plddt"] = compute_plddt(lddt_logits) + + distogram_logits = self.distogram(outputs["pair"]) + aux_out["distogram_logits"] = distogram_logits + + masked_msa_logits = self.masked_msa(outputs["msa"]) + aux_out["masked_msa_logits"] = masked_msa_logits + + experimentally_resolved_logits = self.experimentally_resolved( + outputs["single"] + ) + aux_out[ + "experimentally_resolved_logits" + ] = experimentally_resolved_logits + + if self.config.tm.enabled: + tm_logits = self.tm(outputs["pair"]) + aux_out["tm_logits"] = tm_logits + aux_out["predicted_tm_score"] = compute_tm( + tm_logits, **self.config.tm + ) + aux_out.update( + compute_predicted_aligned_error( + tm_logits, + **self.config.tm, + ) + ) + + return aux_out + + +class PerResidueLDDTCaPredictor(nn.Module): + def __init__(self, no_bins, c_in, c_hidden): + super(PerResidueLDDTCaPredictor, self).__init__() + + self.no_bins = no_bins + self.c_in = c_in + self.c_hidden = c_hidden + + self.layer_norm = LayerNorm(self.c_in) + + self.linear_1 = Linear(self.c_in, self.c_hidden, init="relu") + self.linear_2 = Linear(self.c_hidden, self.c_hidden, init="relu") + self.linear_3 = Linear(self.c_hidden, self.no_bins, init="final") + + self.relu = nn.ReLU() + + def forward(self, s): + s = self.layer_norm(s) + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + s = self.relu(s) + s = self.linear_3(s) + + return s + + +class DistogramHead(nn.Module): + """ + Computes a distogram probability distribution. + + For use in computation of distogram loss, subsection 1.9.8 + """ + + def __init__(self, c_z, no_bins, **kwargs): + """ + Args: + c_z: + Input channel dimension + no_bins: + Number of distogram bins + """ + super(DistogramHead, self).__init__() + + self.c_z = c_z + self.no_bins = no_bins + + self.linear = Linear(self.c_z, self.no_bins, init="final") + + def forward(self, z): # [*, N, N, C_z] + """ + Args: + z: + [*, N_res, N_res, C_z] pair embedding + Returns: + [*, N, N, no_bins] distogram probability distribution + """ + # [*, N, N, no_bins] + logits = self.linear(z) + logits = logits + logits.transpose(-2, -3) + return logits + + +class TMScoreHead(nn.Module): + """ + For use in computation of TM-score, subsection 1.9.7 + """ + + def __init__(self, c_z, no_bins, **kwargs): + """ + Args: + c_z: + Input channel dimension + no_bins: + Number of bins + """ + super(TMScoreHead, self).__init__() + + self.c_z = c_z + self.no_bins = no_bins + + self.linear = Linear(self.c_z, self.no_bins, init="final") + + def forward(self, z): + """ + Args: + z: + [*, N_res, N_res, C_z] pairwise embedding + Returns: + [*, N_res, N_res, no_bins] prediction + """ + # [*, N, N, no_bins] + logits = self.linear(z) + return logits + + +class MaskedMSAHead(nn.Module): + """ + For use in computation of masked MSA loss, subsection 1.9.9 + """ + + def __init__(self, c_m, c_out, **kwargs): + """ + Args: + c_m: + MSA channel dimension + c_out: + Output channel dimension + """ + super(MaskedMSAHead, self).__init__() + + self.c_m = c_m + self.c_out = c_out + + self.linear = Linear(self.c_m, self.c_out, init="final") + + def forward(self, m): + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA embedding + Returns: + [*, N_seq, N_res, C_out] reconstruction + """ + # [*, N_seq, N_res, C_out] + logits = self.linear(m) + return logits + + +class ExperimentallyResolvedHead(nn.Module): + """ + For use in computation of "experimentally resolved" loss, subsection + 1.9.10 + """ + + def __init__(self, c_s, c_out, **kwargs): + """ + Args: + c_s: + Input channel dimension + c_out: + Number of distogram bins + """ + super(ExperimentallyResolvedHead, self).__init__() + + self.c_s = c_s + self.c_out = c_out + + self.linear = Linear(self.c_s, self.c_out, init="final") + + def forward(self, s): + """ + Args: + s: + [*, N_res, C_s] single embedding + Returns: + [*, N, C_out] logits + """ + # [*, N, C_out] + logits = self.linear(s) + return logits diff --git a/gafl/openfold/model/model.py b/gafl/openfold/model/model.py new file mode 100644 index 0000000000000000000000000000000000000000..007b90f7af7b7f5b379f5c18d89f0f69f398c494 --- /dev/null +++ b/gafl/openfold/model/model.py @@ -0,0 +1,446 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +import torch +import torch.nn as nn + +from openfold.utils.feats import ( + pseudo_beta_fn, + build_extra_msa_feat, + build_template_angle_feat, + build_template_pair_feat, + atom14_to_atom37, +) +from openfold.model.embedders import ( + InputEmbedder, + RecyclingEmbedder, + TemplateAngleEmbedder, + TemplatePairEmbedder, + ExtraMSAEmbedder, +) +from openfold.model.evoformer import EvoformerStack, ExtraMSAStack +from openfold.model.heads import AuxiliaryHeads +import openfold.np.residue_constants as residue_constants +from openfold.model.structure_module import StructureModule +from openfold.model.template import ( + TemplatePairStack, + TemplatePointwiseAttention, +) +from openfold.utils.loss import ( + compute_plddt, +) +from openfold.utils.tensor_utils import ( + dict_multimap, + tensor_tree_map, +) + + +class AlphaFold(nn.Module): + """ + Alphafold 2. + + Implements Algorithm 2 (but with training). + """ + + def __init__(self, config): + """ + Args: + config: + A dict-like config object (like the one in config.py) + """ + super(AlphaFold, self).__init__() + + self.globals = config.globals + config = config.model + template_config = config.template + extra_msa_config = config.extra_msa + + # Main trunk + structure module + self.input_embedder = InputEmbedder( + **config["input_embedder"], + ) + self.recycling_embedder = RecyclingEmbedder( + **config["recycling_embedder"], + ) + self.template_angle_embedder = TemplateAngleEmbedder( + **template_config["template_angle_embedder"], + ) + self.template_pair_embedder = TemplatePairEmbedder( + **template_config["template_pair_embedder"], + ) + self.template_pair_stack = TemplatePairStack( + **template_config["template_pair_stack"], + ) + self.template_pointwise_att = TemplatePointwiseAttention( + **template_config["template_pointwise_attention"], + ) + self.extra_msa_embedder = ExtraMSAEmbedder( + **extra_msa_config["extra_msa_embedder"], + ) + self.extra_msa_stack = ExtraMSAStack( + **extra_msa_config["extra_msa_stack"], + ) + self.evoformer = EvoformerStack( + **config["evoformer_stack"], + ) + self.structure_module = StructureModule( + **config["structure_module"], + ) + + self.aux_heads = AuxiliaryHeads( + config["heads"], + ) + + self.config = config + + def embed_templates(self, batch, z, pair_mask, templ_dim): + # Embed the templates one at a time (with a poor man's vmap) + template_embeds = [] + n_templ = batch["template_aatype"].shape[templ_dim] + for i in range(n_templ): + idx = batch["template_aatype"].new_tensor(i) + single_template_feats = tensor_tree_map( + lambda t: torch.index_select(t, templ_dim, idx), + batch, + ) + + single_template_embeds = {} + if self.config.template.embed_angles: + template_angle_feat = build_template_angle_feat( + single_template_feats, + ) + + # [*, S_t, N, C_m] + a = self.template_angle_embedder(template_angle_feat) + + single_template_embeds["angle"] = a + + # [*, S_t, N, N, C_t] + t = build_template_pair_feat( + single_template_feats, + inf=self.config.template.inf, + eps=self.config.template.eps, + **self.config.template.distogram, + ).to(z.dtype) + t = self.template_pair_embedder(t) + + single_template_embeds.update({"pair": t}) + + template_embeds.append(single_template_embeds) + + template_embeds = dict_multimap( + partial(torch.cat, dim=templ_dim), + template_embeds, + ) + + # [*, S_t, N, N, C_z] + t = self.template_pair_stack( + template_embeds["pair"], + pair_mask.unsqueeze(-3).to(dtype=z.dtype), + chunk_size=self.globals.chunk_size, + _mask_trans=self.config._mask_trans, + ) + + # [*, N, N, C_z] + t = self.template_pointwise_att( + t, + z, + template_mask=batch["template_mask"].to(dtype=z.dtype), + chunk_size=self.globals.chunk_size, + ) + t = t * (torch.sum(batch["template_mask"]) > 0) + + ret = {} + if self.config.template.embed_angles: + ret["template_angle_embedding"] = template_embeds["angle"] + + ret.update({"template_pair_embedding": t}) + + return ret + + def iteration(self, feats, m_1_prev, z_prev, x_prev, _recycle=True): + # Primary output dictionary + outputs = {} + + # This needs to be done manually for DeepSpeed's sake + dtype = next(self.parameters()).dtype + for k in feats: + if(feats[k].dtype == torch.float32): + feats[k] = feats[k].to(dtype=dtype) + + # Grab some data about the input + batch_dims = feats["target_feat"].shape[:-2] + no_batch_dims = len(batch_dims) + n = feats["target_feat"].shape[-2] + n_seq = feats["msa_feat"].shape[-3] + device = feats["target_feat"].device + + # Prep some features + seq_mask = feats["seq_mask"] + pair_mask = seq_mask[..., None] * seq_mask[..., None, :] + msa_mask = feats["msa_mask"] + + # Initialize the MSA and pair representations + + # m: [*, S_c, N, C_m] + # z: [*, N, N, C_z] + m, z = self.input_embedder( + feats["target_feat"], + feats["residue_index"], + feats["msa_feat"], + ) + + # Initialize the recycling embeddings, if needs be + if None in [m_1_prev, z_prev, x_prev]: + # [*, N, C_m] + m_1_prev = m.new_zeros( + (*batch_dims, n, self.config.input_embedder.c_m), + requires_grad=False, + ) + + # [*, N, N, C_z] + z_prev = z.new_zeros( + (*batch_dims, n, n, self.config.input_embedder.c_z), + requires_grad=False, + ) + + # [*, N, 3] + x_prev = z.new_zeros( + (*batch_dims, n, residue_constants.atom_type_num, 3), + requires_grad=False, + ) + + x_prev = pseudo_beta_fn( + feats["aatype"], x_prev, None + ).to(dtype=z.dtype) + + # m_1_prev_emb: [*, N, C_m] + # z_prev_emb: [*, N, N, C_z] + m_1_prev_emb, z_prev_emb = self.recycling_embedder( + m_1_prev, + z_prev, + x_prev, + ) + + # If the number of recycling iterations is 0, skip recycling + # altogether. We zero them this way instead of computing them + # conditionally to avoid leaving parameters unused, which has annoying + # implications for DDP training. + if(not _recycle): + m_1_prev_emb *= 0 + z_prev_emb *= 0 + + # [*, S_c, N, C_m] + m[..., 0, :, :] += m_1_prev_emb + + # [*, N, N, C_z] + z += z_prev_emb + + # Possibly prevents memory fragmentation + del m_1_prev, z_prev, x_prev, m_1_prev_emb, z_prev_emb + + # Embed the templates + merge with MSA/pair embeddings + if self.config.template.enabled: + template_feats = { + k: v for k, v in feats.items() if k.startswith("template_") + } + template_embeds = self.embed_templates( + template_feats, + z, + pair_mask.to(dtype=z.dtype), + no_batch_dims, + ) + + # [*, N, N, C_z] + z = z + template_embeds["template_pair_embedding"] + + if self.config.template.embed_angles: + # [*, S = S_c + S_t, N, C_m] + m = torch.cat( + [m, template_embeds["template_angle_embedding"]], + dim=-3 + ) + + # [*, S, N] + torsion_angles_mask = feats["template_torsion_angles_mask"] + msa_mask = torch.cat( + [feats["msa_mask"], torsion_angles_mask[..., 2]], + dim=-2 + ) + + # Embed extra MSA features + merge with pairwise embeddings + if self.config.extra_msa.enabled: + # [*, S_e, N, C_e] + a = self.extra_msa_embedder(build_extra_msa_feat(feats)) + + # [*, N, N, C_z] + z = self.extra_msa_stack( + a, + z, + msa_mask=feats["extra_msa_mask"].to(dtype=a.dtype), + chunk_size=self.globals.chunk_size, + pair_mask=pair_mask.to(dtype=z.dtype), + _mask_trans=self.config._mask_trans, + ) + + # Run MSA + pair embeddings through the trunk of the network + # m: [*, S, N, C_m] + # z: [*, N, N, C_z] + # s: [*, N, C_s] + m, z, s = self.evoformer( + m, + z, + msa_mask=msa_mask.to(dtype=m.dtype), + pair_mask=pair_mask.to(dtype=z.dtype), + chunk_size=self.globals.chunk_size, + _mask_trans=self.config._mask_trans, + ) + + outputs["msa"] = m[..., :n_seq, :, :] + outputs["pair"] = z + outputs["single"] = s + + # Predict 3D structure + outputs["sm"] = self.structure_module( + s, + z, + feats["aatype"], + mask=feats["seq_mask"].to(dtype=s.dtype), + ) + outputs["final_atom_positions"] = atom14_to_atom37( + outputs["sm"]["positions"][-1], feats + ) + outputs["final_atom_mask"] = feats["atom37_atom_exists"] + outputs["final_affine_tensor"] = outputs["sm"]["frames"][-1] + + # Save embeddings for use during the next recycling iteration + + # [*, N, C_m] + m_1_prev = m[..., 0, :, :] + + # [*, N, N, C_z] + z_prev = z + + # [*, N, 3] + x_prev = outputs["final_atom_positions"] + + return outputs, m_1_prev, z_prev, x_prev + + def _disable_activation_checkpointing(self): + self.template_pair_stack.blocks_per_ckpt = None + self.evoformer.blocks_per_ckpt = None + + for b in self.extra_msa_stack.blocks: + b.ckpt = False + + def _enable_activation_checkpointing(self): + self.template_pair_stack.blocks_per_ckpt = ( + self.config.template.template_pair_stack.blocks_per_ckpt + ) + self.evoformer.blocks_per_ckpt = ( + self.config.evoformer_stack.blocks_per_ckpt + ) + + for b in self.extra_msa_stack.blocks: + b.ckpt = self.config.extra_msa.extra_msa_stack.ckpt + + def forward(self, batch): + """ + Args: + batch: + Dictionary of arguments outlined in Algorithm 2. Keys must + include the official names of the features in the + supplement subsection 1.2.9. + + The final dimension of each input must have length equal to + the number of recycling iterations. + + Features (without the recycling dimension): + + "aatype" ([*, N_res]): + Contrary to the supplement, this tensor of residue + indices is not one-hot. + "target_feat" ([*, N_res, C_tf]) + One-hot encoding of the target sequence. C_tf is + config.model.input_embedder.tf_dim. + "residue_index" ([*, N_res]) + Tensor whose final dimension consists of + consecutive indices from 0 to N_res. + "msa_feat" ([*, N_seq, N_res, C_msa]) + MSA features, constructed as in the supplement. + C_msa is config.model.input_embedder.msa_dim. + "seq_mask" ([*, N_res]) + 1-D sequence mask + "msa_mask" ([*, N_seq, N_res]) + MSA mask + "pair_mask" ([*, N_res, N_res]) + 2-D pair mask + "extra_msa_mask" ([*, N_extra, N_res]) + Extra MSA mask + "template_mask" ([*, N_templ]) + Template mask (on the level of templates, not + residues) + "template_aatype" ([*, N_templ, N_res]) + Tensor of template residue indices (indices greater + than 19 are clamped to 20 (Unknown)) + "template_all_atom_positions" + ([*, N_templ, N_res, 37, 3]) + Template atom coordinates in atom37 format + "template_all_atom_mask" ([*, N_templ, N_res, 37]) + Template atom coordinate mask + "template_pseudo_beta" ([*, N_templ, N_res, 3]) + Positions of template carbon "pseudo-beta" atoms + (i.e. C_beta for all residues but glycine, for + for which C_alpha is used instead) + "template_pseudo_beta_mask" ([*, N_templ, N_res]) + Pseudo-beta mask + """ + # Initialize recycling embeddings + m_1_prev, z_prev, x_prev = None, None, None + + # Disable activation checkpointing for the first few recycling iters + is_grad_enabled = torch.is_grad_enabled() + self._disable_activation_checkpointing() + + # Main recycling loop + num_iters = batch["aatype"].shape[-1] + for cycle_no in range(num_iters): + # Select the features for the current recycling cycle + fetch_cur_batch = lambda t: t[..., cycle_no] + feats = tensor_tree_map(fetch_cur_batch, batch) + + # Enable grad iff we're training and it's the final recycling layer + is_final_iter = cycle_no == (num_iters - 1) + with torch.set_grad_enabled(is_grad_enabled and is_final_iter): + if is_final_iter: + self._enable_activation_checkpointing() + # Sidestep AMP bug (PyTorch issue #65766) + if torch.is_autocast_enabled(): + torch.clear_autocast_cache() + + # Run the next iteration of the model + outputs, m_1_prev, z_prev, x_prev = self.iteration( + feats, + m_1_prev, + z_prev, + x_prev, + _recycle=(num_iters > 1) + ) + + # Run auxiliary heads + outputs.update(self.aux_heads(outputs)) + + return outputs diff --git a/gafl/openfold/model/msa.py b/gafl/openfold/model/msa.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3936f296a8cd5b7fa7f28a9d941668b2bd6c66 --- /dev/null +++ b/gafl/openfold/model/msa.py @@ -0,0 +1,392 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import torch +import torch.nn as nn +from typing import Optional, List, Tuple + +from openfold.model.primitives import ( + Linear, + LayerNorm, + Attention, + GlobalAttention, + _attention_chunked_trainable, +) +from openfold.utils.checkpointing import get_checkpoint_fn +from openfold.utils.tensor_utils import ( + chunk_layer, + permute_final_dims, + flatten_final_dims, +) + + +class MSAAttention(nn.Module): + def __init__( + self, + c_in, + c_hidden, + no_heads, + pair_bias=False, + c_z=None, + inf=1e9, + ): + """ + Args: + c_in: + Input channel dimension + c_hidden: + Per-head hidden channel dimension + no_heads: + Number of attention heads + pair_bias: + Whether to use pair embedding bias + c_z: + Pair embedding channel dimension. Ignored unless pair_bias + is true + inf: + A large number to be used in computing the attention mask + """ + super(MSAAttention, self).__init__() + + self.c_in = c_in + self.c_hidden = c_hidden + self.no_heads = no_heads + self.pair_bias = pair_bias + self.c_z = c_z + self.inf = inf + + self.layer_norm_m = LayerNorm(self.c_in) + + self.layer_norm_z = None + self.linear_z = None + if self.pair_bias: + self.layer_norm_z = LayerNorm(self.c_z) + self.linear_z = Linear( + self.c_z, self.no_heads, bias=False, init="normal" + ) + + self.mha = Attention( + self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads + ) + + @torch.jit.ignore + def _chunk(self, + m: torch.Tensor, + biases: List[torch.Tensor], + chunk_size: int, + ) -> torch.Tensor: + return chunk_layer( + self.mha, + {"q_x": m, "kv_x": m, "biases": biases}, + chunk_size=chunk_size, + no_batch_dims=len(m.shape[:-2]), + ) + + def _prep_inputs(self, + m: torch.Tensor, + z: Optional[torch.Tensor], + mask: Optional[torch.Tensor] + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # [*, N_seq, N_res, C_m] + m = self.layer_norm_m(m) + + n_seq, n_res = m.shape[-3:-1] + if mask is None: + # [*, N_seq, N_res] + mask = m.new_ones( + m.shape[:-3] + (n_seq, n_res), + ) + + # [*, N_seq, 1, 1, N_res] + mask_bias = (self.inf * (mask - 1))[..., :, None, None, :] + + # This step simply returns a larger view of the bias, and does not + # consume additional memory. + # [*, N_seq, no_heads, N_res, N_res] + #bias = bias.expand( + # ((-1,) * len(bias.shape[:-4])) + (-1, self.no_heads, n_res, -1) + #) + + if (self.pair_bias and + z is not None and # For the + self.layer_norm_z is not None and # benefit of + self.linear_z is not None # TorchScript + ): + # [*, N_res, N_res, C_z] + z = self.layer_norm_z(z) + + # [*, N_res, N_res, no_heads] + z = self.linear_z(z) + + # [*, 1, no_heads, N_res, N_res] + z = permute_final_dims(z, (2, 0, 1)).unsqueeze(-4) + + return m, mask_bias, z + + @torch.jit.ignore + def _chunked_msa_attn(self, + m: torch.Tensor, + z: Optional[torch.Tensor], + mask: Optional[torch.Tensor], + chunk_logits: int, + checkpoint: bool, + ) -> torch.Tensor: + MSA_DIM = -4 + + def _get_qkv(m, z): + m, mask_bias, z = self._prep_inputs(m, z, mask) + q, k, v = self.mha._prep_qkv(m, m) + return m, q, k, v, mask_bias, z + + checkpoint_fn = get_checkpoint_fn() + + if(torch.is_grad_enabled() and checkpoint): + m, q, k, v, mask_bias, z = checkpoint_fn(_get_qkv, m, z) + else: + m, q, k, v, mask_bias, z = _get_qkv(m, z) + + o = _attention_chunked_trainable( + query=q, + key=k, + value=v, + biases=[mask_bias, z], + chunk_size=chunk_logits, + chunk_dim=MSA_DIM, + checkpoint=checkpoint, + ) + + if(torch.is_grad_enabled() and checkpoint): + # Storing an additional m here is far from ideal + m = checkpoint_fn(self.mha._wrap_up, o, m) + else: + m = self.mha._wrap_up(o, m) + + return m + + def forward(self, + m: torch.Tensor, + z: Optional[torch.Tensor] = None, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None, + _chunk_logits: Optional[int] = None, + _checkpoint_chunks: Optional[bool] = None, + ) -> torch.Tensor: + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA embedding + z: + [*, N_res, N_res, C_z] pair embedding. Required only if + pair_bias is True + mask: + [*, N_seq, N_res] MSA mask + chunk_size: + Size of chunks into which the inputs are split along their + batch dimensions. A low value decreases memory overhead at the + cost of slower execution. Chunking is not performed by default. + + """ + if(_chunk_logits is not None): + return self._chunked_msa_attn( + m=m, z=z, mask=mask, + chunk_logits=_chunk_logits, checkpoint=_checkpoint_chunks + ) + + m, mask_bias, z = self._prep_inputs(m, z, mask) + + biases = [mask_bias] + if(z is not None): + biases.append(z) + + if chunk_size is not None: + m = self._chunk(m, biases, chunk_size) + else: + m = self.mha( + q_x=m, + kv_x=m, + biases=biases + ) + + return m + + +class MSARowAttentionWithPairBias(MSAAttention): + """ + Implements Algorithm 7. + """ + + def __init__(self, c_m, c_z, c_hidden, no_heads, inf=1e9): + """ + Args: + c_m: + Input channel dimension + c_z: + Pair embedding channel dimension + c_hidden: + Per-head hidden channel dimension + no_heads: + Number of attention heads + inf: + Large number used to construct attention masks + """ + super(MSARowAttentionWithPairBias, self).__init__( + c_m, + c_hidden, + no_heads, + pair_bias=True, + c_z=c_z, + inf=inf, + ) + + +class MSAColumnAttention(nn.Module): + """ + Implements Algorithm 8. + + By rights, this should also be a subclass of MSAAttention. Alas, + most inheritance isn't supported by TorchScript. + """ + + def __init__(self, c_m, c_hidden, no_heads, inf=1e9): + """ + Args: + c_m: + MSA channel dimension + c_hidden: + Per-head hidden channel dimension + no_heads: + Number of attention heads + inf: + Large number used to construct attention masks + """ + super(MSAColumnAttention, self).__init__() + + self.c_m = c_m + self.c_hidden = c_hidden + self.no_heads = no_heads + self.inf = inf + + self._msa_att = MSAAttention( + c_in=c_m, + c_hidden=c_hidden, + no_heads=no_heads, + pair_bias=False, + c_z=None, + inf=inf, + ) + + def forward(self, + m: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None + ) -> torch.Tensor: + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA embedding + mask: + [*, N_seq, N_res] MSA mask + chunk_size: + Size of chunks into which the inputs are split along their + batch dimensions. A low value decreases memory overhead at the + cost of slower execution. Chunking is not performed by default. + """ + # [*, N_res, N_seq, C_in] + m = m.transpose(-2, -3) + if mask is not None: + mask = mask.transpose(-1, -2) + + m = self._msa_att(m, mask=mask, chunk_size=chunk_size) + + # [*, N_seq, N_res, C_in] + m = m.transpose(-2, -3) + if mask is not None: + mask = mask.transpose(-1, -2) + + return m + + +class MSAColumnGlobalAttention(nn.Module): + def __init__( + self, c_in, c_hidden, no_heads, inf=1e9, eps=1e-10, + ): + super(MSAColumnGlobalAttention, self).__init__() + + self.c_in = c_in + self.c_hidden = c_hidden + self.no_heads = no_heads + self.inf = inf + self.eps = eps + + self.layer_norm_m = nn.LayerNorm(c_in) + + self.global_attention = GlobalAttention( + c_in=c_in, + c_hidden=c_hidden, + no_heads=no_heads, + inf=inf, + eps=eps, + ) + + @torch.jit.ignore + def _chunk(self, + m: torch.Tensor, + mask: torch.Tensor, + chunk_size: int, + ) -> torch.Tensor: + mha_input = { + "m": m, + "mask": mask, + } + return chunk_layer( + self.global_attention, + mha_input, + chunk_size=chunk_size, + no_batch_dims=len(m.shape[:-2]), + ) + + def forward( + self, + m: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None, + ) -> torch.Tensor: + n_seq, n_res, c_in = m.shape[-3:] + + if mask is None: + # [*, N_seq, N_res] + mask = torch.ones( + m.shape[:-1], + dtype=m.dtype, + device=m.device, + ).detach() + + # [*, N_res, N_seq, C_in] + m = m.transpose(-2, -3) + mask = mask.transpose(-1, -2) + + # [*, N_res, N_seq, C_in] + m = self.layer_norm_m(m) + + if chunk_size is not None: + m = self._chunk(m, mask, chunk_size) + else: + m = self.global_attention(m=m, mask=mask) + + # [*, N_seq, N_res, C_in] + m = m.transpose(-2, -3) + + return m diff --git a/gafl/openfold/model/outer_product_mean.py b/gafl/openfold/model/outer_product_mean.py new file mode 100644 index 0000000000000000000000000000000000000000..2edef22e13235b1d40e403176b5b41828e10832f --- /dev/null +++ b/gafl/openfold/model/outer_product_mean.py @@ -0,0 +1,129 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +from typing import Optional + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear +from openfold.utils.tensor_utils import chunk_layer + + +class OuterProductMean(nn.Module): + """ + Implements Algorithm 10. + """ + + def __init__(self, c_m, c_z, c_hidden, eps=1e-3): + """ + Args: + c_m: + MSA embedding channel dimension + c_z: + Pair embedding channel dimension + c_hidden: + Hidden channel dimension + """ + super(OuterProductMean, self).__init__() + + self.c_m = c_m + self.c_z = c_z + self.c_hidden = c_hidden + self.eps = eps + + self.layer_norm = nn.LayerNorm(c_m) + self.linear_1 = Linear(c_m, c_hidden) + self.linear_2 = Linear(c_m, c_hidden) + self.linear_out = Linear(c_hidden ** 2, c_z, init="final") + + def _opm(self, a, b): + # [*, N_res, N_res, C, C] + outer = torch.einsum("...bac,...dae->...bdce", a, b) + + # [*, N_res, N_res, C * C] + outer = outer.reshape(outer.shape[:-2] + (-1,)) + + # [*, N_res, N_res, C_z] + outer = self.linear_out(outer) + + return outer + + @torch.jit.ignore + def _chunk(self, + a: torch.Tensor, + b: torch.Tensor, + chunk_size: int + ) -> torch.Tensor: + # Since the "batch dim" in this case is not a true batch dimension + # (in that the shape of the output depends on it), we need to + # iterate over it ourselves + a_reshape = a.reshape((-1,) + a.shape[-3:]) + b_reshape = b.reshape((-1,) + b.shape[-3:]) + out = [] + for a_prime, b_prime in zip(a_reshape, b_reshape): + outer = chunk_layer( + partial(self._opm, b=b_prime), + {"a": a_prime}, + chunk_size=chunk_size, + no_batch_dims=1, + ) + out.append(outer) + outer = torch.stack(out, dim=0) + outer = outer.reshape(a.shape[:-3] + outer.shape[1:]) + + return outer + + def forward(self, + m: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None + ) -> torch.Tensor: + """ + Args: + m: + [*, N_seq, N_res, C_m] MSA embedding + mask: + [*, N_seq, N_res] MSA mask + Returns: + [*, N_res, N_res, C_z] pair embedding update + """ + if mask is None: + mask = m.new_ones(m.shape[:-1]) + + # [*, N_seq, N_res, C_m] + m = self.layer_norm(m) + + # [*, N_seq, N_res, C] + mask = mask.unsqueeze(-1) + a = self.linear_1(m) * mask + b = self.linear_2(m) * mask + + a = a.transpose(-2, -3) + b = b.transpose(-2, -3) + + if chunk_size is not None: + outer = self._chunk(a, b, chunk_size) + else: + outer = self._opm(a, b) + + # [*, N_res, N_res, 1] + norm = torch.einsum("...abc,...adc->...bdc", mask, mask) + + # [*, N_res, N_res, C_z] + outer = outer / (self.eps + norm) + + return outer diff --git a/gafl/openfold/model/pair_transition.py b/gafl/openfold/model/pair_transition.py new file mode 100644 index 0000000000000000000000000000000000000000..c81d2a4c0e087ffdb0c98d8cb0e91c5b24d6a0e8 --- /dev/null +++ b/gafl/openfold/model/pair_transition.py @@ -0,0 +1,99 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear, LayerNorm +from openfold.utils.tensor_utils import chunk_layer + + +class PairTransition(nn.Module): + """ + Implements Algorithm 15. + """ + + def __init__(self, c_z, n): + """ + Args: + c_z: + Pair transition channel dimension + n: + Factor by which c_z is multiplied to obtain hidden channel + dimension + """ + super(PairTransition, self).__init__() + + self.c_z = c_z + self.n = n + + self.layer_norm = LayerNorm(self.c_z) + self.linear_1 = Linear(self.c_z, self.n * self.c_z, init="relu") + self.relu = nn.ReLU() + self.linear_2 = Linear(self.n * self.c_z, c_z, init="final") + + def _transition(self, z, mask): + # [*, N_res, N_res, C_hidden] + z = self.linear_1(z) + z = self.relu(z) + + # [*, N_res, N_res, C_z] + z = self.linear_2(z) * mask + + return z + + @torch.jit.ignore + def _chunk(self, + z: torch.Tensor, + mask: torch.Tensor, + chunk_size: int, + ) -> torch.Tensor: + return chunk_layer( + self._transition, + {"z": z, "mask": mask}, + chunk_size=chunk_size, + no_batch_dims=len(z.shape[:-2]), + ) + + + def forward(self, + z: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None, + ) -> torch.Tensor: + """ + Args: + z: + [*, N_res, N_res, C_z] pair embedding + Returns: + [*, N_res, N_res, C_z] pair embedding update + """ + # DISCREPANCY: DeepMind forgets to apply the mask in this module. + if mask is None: + mask = z.new_ones(z.shape[:-1]) + + # [*, N_res, N_res, 1] + mask = mask.unsqueeze(-1) + + # [*, N_res, N_res, C_z] + z = self.layer_norm(z) + + if chunk_size is not None: + z = self._chunk(z, mask, chunk_size) + else: + z = self._transition(z=z, mask=mask) + + return z diff --git a/gafl/openfold/model/primitives.py b/gafl/openfold/model/primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..0742038e49b327661c3b6a137918f500e883cd04 --- /dev/null +++ b/gafl/openfold/model/primitives.py @@ -0,0 +1,587 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +import math +from typing import Optional, Callable, List, Tuple, Sequence +import numpy as np + +import deepspeed +import torch +import torch.nn as nn +from scipy.stats import truncnorm + +from openfold.utils.checkpointing import get_checkpoint_fn +from openfold.utils.tensor_utils import ( + permute_final_dims, + flatten_final_dims, + _chunk_slice, +) + + +def _prod(nums): + out = 1 + for n in nums: + out = out * n + return out + + +def _calculate_fan(linear_weight_shape, fan="fan_in"): + fan_out, fan_in = linear_weight_shape + + if fan == "fan_in": + f = fan_in + elif fan == "fan_out": + f = fan_out + elif fan == "fan_avg": + f = (fan_in + fan_out) / 2 + else: + raise ValueError("Invalid fan option") + + return f + + +def trunc_normal_init_(weights, scale=1.0, fan="fan_in"): + shape = weights.shape + f = _calculate_fan(shape, fan) + scale = scale / max(1, f) + a = -2 + b = 2 + std = math.sqrt(scale) / truncnorm.std(a=a, b=b, loc=0, scale=1) + size = _prod(shape) + samples = truncnorm.rvs(a=a, b=b, loc=0, scale=std, size=size) + samples = np.reshape(samples, shape) + with torch.no_grad(): + weights.copy_(torch.tensor(samples, device=weights.device)) + + +def lecun_normal_init_(weights): + trunc_normal_init_(weights, scale=1.0) + + +def he_normal_init_(weights): + trunc_normal_init_(weights, scale=2.0) + + +def glorot_uniform_init_(weights): + nn.init.xavier_uniform_(weights, gain=1) + + +def final_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def gating_init_(weights): + with torch.no_grad(): + weights.fill_(0.0) + + +def normal_init_(weights): + torch.nn.init.kaiming_normal_(weights, nonlinearity="linear") + + +def ipa_point_weights_init_(weights): + with torch.no_grad(): + softplus_inverse_1 = 0.541324854612918 + weights.fill_(softplus_inverse_1) + + +class Linear(nn.Linear): + """ + A Linear layer with built-in nonstandard initializations. Called just + like torch.nn.Linear. + + Implements the initializers in 1.11.4, plus some additional ones found + in the code. + """ + + def __init__( + self, + in_dim: int, + out_dim: int, + bias: bool = True, + init: str = "default", + init_fn: Optional[Callable[[torch.Tensor, torch.Tensor], None]] = None, + ): + """ + Args: + in_dim: + The final dimension of inputs to the layer + out_dim: + The final dimension of layer outputs + bias: + Whether to learn an additive bias. True by default + init: + The initializer to use. Choose from: + + "default": LeCun fan-in truncated normal initialization + "relu": He initialization w/ truncated normal distribution + "glorot": Fan-average Glorot uniform initialization + "gating": Weights=0, Bias=1 + "normal": Normal initialization with std=1/sqrt(fan_in) + "final": Weights=0, Bias=0 + + Overridden by init_fn if the latter is not None. + init_fn: + A custom initializer taking weight and bias as inputs. + Overrides init if not None. + """ + super(Linear, self).__init__(in_dim, out_dim, bias=bias) + + if bias: + with torch.no_grad(): + self.bias.fill_(0) + + if init_fn is not None: + init_fn(self.weight, self.bias) + else: + if init == "default": + lecun_normal_init_(self.weight) + elif init == "relu": + he_normal_init_(self.weight) + elif init == "glorot": + glorot_uniform_init_(self.weight) + elif init == "gating": + gating_init_(self.weight) + if bias: + with torch.no_grad(): + self.bias.fill_(1.0) + elif init == "normal": + normal_init_(self.weight) + elif init == "final": + final_init_(self.weight) + else: + raise ValueError("Invalid init string.") + + +class LayerNorm(nn.Module): + def __init__(self, c_in, eps=1e-5): + super(LayerNorm, self).__init__() + + self.c_in = (c_in,) + self.eps = eps + + self.weight = nn.Parameter(torch.ones(c_in)) + self.bias = nn.Parameter(torch.zeros(c_in)) + + def forward(self, x): + d = x.dtype + if(d is torch.bfloat16 and not deepspeed.utils.is_initialized()): + with torch.cuda.amp.autocast(enabled=False): + out = nn.functional.layer_norm( + x, + self.c_in, + self.weight.to(dtype=d), + self.bias.to(dtype=d), + self.eps + ) + else: + out = nn.functional.layer_norm( + x, + self.c_in, + self.weight, + self.bias, + self.eps, + ) + + return out + +@torch.jit.ignore +def softmax(t: torch.Tensor, dim: int = -1) -> torch.Tensor: + """ + Softmax, but without automatic casting to fp32 when the input is of + type bfloat16 + """ + d = t.dtype + if(d is torch.bfloat16 and not deepspeed.utils.is_initialized()): + with torch.cuda.amp.autocast(enabled=False): + s = torch.nn.functional.softmax(t, dim=dim) + else: + s = torch.nn.functional.softmax(t, dim=dim) + + return s + + +#@torch.jit.script +def _attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, biases: List[torch.Tensor]) -> torch.Tensor: + # [*, H, Q, C_hidden] + query = permute_final_dims(query, (1, 0, 2)) + + # [*, H, C_hidden, K] + key = permute_final_dims(key, (1, 2, 0)) + + # [*, H, V, C_hidden] + value = permute_final_dims(value, (1, 0, 2)) + + # [*, H, Q, K] + a = torch.matmul(query, key) + + for b in biases: + a += b + + a = softmax(a, -1) + + # [*, H, Q, C_hidden] + a = torch.matmul(a, value) + + # [*, Q, H, C_hidden] + a = a.transpose(-2, -3) + + return a + + +@torch.jit.ignore +def _attention_chunked_trainable( + query, key, value, biases, chunk_size, chunk_dim, checkpoint, +): + if(checkpoint and len(biases) > 2): + raise ValueError( + "Checkpointed version permits only permits two bias terms" + ) + + def _checkpointable_attention(q, k, v, b1, b2): + bs = [b for b in [b1, b2] if b is not None] + return _attention(q, k, v, bs) + + o_chunks = [] + checkpoint_fn = get_checkpoint_fn() + count = query.shape[chunk_dim] + for start in range(0, count, chunk_size): + end = start + chunk_size + idx = [slice(None)] * len(query.shape) + idx[chunk_dim] = slice(start, end) + idx_tup = tuple(idx) + q_chunk = query[idx_tup] + k_chunk = key[idx_tup] + v_chunk = value[idx_tup] + + def _slice_bias(b): + idx[chunk_dim] = ( + slice(start, end) if b.shape[chunk_dim] != 1 else slice(None) + ) + return b[tuple(idx)] + + if(checkpoint): + bias_1_chunk, bias_2_chunk = [ + _slice_bias(b) if b is not None else None + for b in (biases + [None, None])[:2] + ] + + o_chunk = checkpoint_fn(_checkpointable_attention, + q_chunk, k_chunk, v_chunk, bias_1_chunk, bias_2_chunk + ) + else: + bias_chunks = [ + _slice_bias(b) for b in biases + ] + + o_chunk = _attention(q_chunk, k_chunk, v_chunk, bias_chunks) + + o_chunks.append(o_chunk) + + o = torch.cat(o_chunks, dim=chunk_dim) + return o + + +class Attention(nn.Module): + """ + Standard multi-head attention using AlphaFold's default layer + initialization. Allows multiple bias vectors. + """ + def __init__( + self, + c_q: int, + c_k: int, + c_v: int, + c_hidden: int, + no_heads: int, + gating: bool = True, + ): + """ + Args: + c_q: + Input dimension of query data + c_k: + Input dimension of key data + c_v: + Input dimension of value data + c_hidden: + Per-head hidden dimension + no_heads: + Number of attention heads + gating: + Whether the output should be gated using query data + """ + super(Attention, self).__init__() + + self.c_q = c_q + self.c_k = c_k + self.c_v = c_v + self.c_hidden = c_hidden + self.no_heads = no_heads + self.gating = gating + + # DISCREPANCY: c_hidden is not the per-head channel dimension, as + # stated in the supplement, but the overall channel dimension. + + self.linear_q = Linear( + self.c_q, self.c_hidden * self.no_heads, bias=False, init="glorot" + ) + self.linear_k = Linear( + self.c_k, self.c_hidden * self.no_heads, bias=False, init="glorot" + ) + self.linear_v = Linear( + self.c_v, self.c_hidden * self.no_heads, bias=False, init="glorot" + ) + self.linear_o = Linear( + self.c_hidden * self.no_heads, self.c_q, init="final" + ) + + self.linear_g = None + if self.gating: + self.linear_g = Linear( + self.c_q, self.c_hidden * self.no_heads, init="gating" + ) + + self.sigmoid = nn.Sigmoid() + + def _prep_qkv(self, + q_x: torch.Tensor, + kv_x: torch.Tensor + ) -> Tuple[ + torch.Tensor, torch.Tensor, torch.Tensor + ]: + # [*, Q/K/V, H * C_hidden] + q = self.linear_q(q_x) + k = self.linear_k(kv_x) + v = self.linear_v(kv_x) + + # [*, Q/K, H, C_hidden] + q = q.view(q.shape[:-1] + (self.no_heads, -1)) + k = k.view(k.shape[:-1] + (self.no_heads, -1)) + v = v.view(v.shape[:-1] + (self.no_heads, -1)) + + q /= math.sqrt(self.c_hidden) + + return q, k, v + + def _wrap_up(self, + o: torch.Tensor, + q_x: torch.Tensor + ) -> torch.Tensor: + if(self.linear_g is not None): + g = self.sigmoid(self.linear_g(q_x)) + + # [*, Q, H, C_hidden] + g = g.view(g.shape[:-1] + (self.no_heads, -1)) + o = o * g + + # [*, Q, H * C_hidden] + o = flatten_final_dims(o, 2) + + # [*, Q, C_q] + o = self.linear_o(o) + + return o + + def forward( + self, + q_x: torch.Tensor, + kv_x: torch.Tensor, + biases: Optional[List[torch.Tensor]] = None, + use_lma: bool = False, + q_chunk_size: Optional[int] = None, + kv_chunk_size: Optional[int] = None, + ) -> torch.Tensor: + """ + Args: + q_x: + [*, Q, C_q] query data + kv_x: + [*, K, C_k] key data + biases: + List of biases that broadcast to [*, H, Q, K] + use_lma: + Whether to use low-memory attention + q_chunk_size: + Query chunk size (for LMA) + kv_chunk_size: + Key/Value chunk size (for LMA) + Returns + [*, Q, C_q] attention update + """ + if(biases is None): + biases = [] + if(use_lma and (q_chunk_size is None or kv_chunk_size is None)): + raise ValueError( + "If use_lma is specified, q_chunk_size and kv_chunk_size must " + "be provided" + ) + + q, k, v = self._prep_qkv(q_x, kv_x) + + if(use_lma): + biases = [ + b.expand(b.shape[:-2] + (q_x.shape[-2],) + (kv_x.shape[-2],)) + for b in biases + ] + + o = _lma(q, k, v, biases, q_chunk_size, kv_chunk_size) + else: + o = _attention(q, k, v, biases) + + o = self._wrap_up(o, q_x) + + return o + + +class GlobalAttention(nn.Module): + def __init__(self, c_in, c_hidden, no_heads, inf, eps): + super(GlobalAttention, self).__init__() + + self.c_in = c_in + self.c_hidden = c_hidden + self.no_heads = no_heads + self.inf = inf + self.eps = eps + + self.linear_q = Linear( + c_in, c_hidden * no_heads, bias=False, init="glorot" + ) + + self.linear_k = Linear( + c_in, c_hidden, bias=False, init="glorot", + ) + self.linear_v = Linear( + c_in, c_hidden, bias=False, init="glorot", + ) + self.linear_g = Linear(c_in, c_hidden * no_heads, init="gating") + self.linear_o = Linear(c_hidden * no_heads, c_in, init="final") + + self.sigmoid = nn.Sigmoid() + + def forward(self, m: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + # [*, N_res, C_in] + q = torch.sum(m * mask.unsqueeze(-1), dim=-2) / ( + torch.sum(mask, dim=-1)[..., None] + self.eps + ) + + # [*, N_res, H * C_hidden] + q = self.linear_q(q) + q *= (self.c_hidden ** (-0.5)) + + # [*, N_res, H, C_hidden] + q = q.view(q.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, N_seq, C_hidden] + k = self.linear_k(m) + v = self.linear_v(m) + + # [*, N_res, H, N_seq] + a = torch.matmul( + q, + k.transpose(-1, -2), # [*, N_res, C_hidden, N_seq] + ) + bias = (self.inf * (mask - 1))[..., :, None, :] + a += bias + a = softmax(a) + + # [*, N_res, H, C_hidden] + o = torch.matmul( + a, + v, + ) + + # [*, N_res, N_seq, C_hidden] + g = self.sigmoid(self.linear_g(m)) + + # [*, N_res, N_seq, H, C_hidden] + g = g.view(g.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, N_seq, H, C_hidden] + o = o.unsqueeze(-3) * g + + # [*, N_res, N_seq, H * C_hidden] + o = o.reshape(o.shape[:-2] + (-1,)) + + # [*, N_res, N_seq, C_in] + m = self.linear_o(o) + + return m + + +def _lma( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + biases: List[torch.Tensor], + q_chunk_size: int, + kv_chunk_size: int, +): + no_q, no_kv = q.shape[-3], k.shape[-3] + + # [*, Q, H, C_hidden] + o = q.new_zeros(q.shape) + for q_s in range(0, no_q, q_chunk_size): + q_chunk = q[..., q_s: q_s + q_chunk_size, :, :] + large_bias_chunks = [ + b[..., q_s: q_s + q_chunk_size, :] for b in biases + ] + + maxes = [] + weights = [] + values = [] + for kv_s in range(0, no_kv, kv_chunk_size): + k_chunk = k[..., kv_s: kv_s + kv_chunk_size, :, :] + v_chunk = v[..., kv_s: kv_s + kv_chunk_size, :, :] + small_bias_chunks = [ + b[..., kv_s: kv_s + kv_chunk_size] for b in large_bias_chunks + ] + + a = torch.einsum( + "...qhd,...khd->...hqk", q_chunk, k_chunk, + ) + + for b in small_bias_chunks: + a += b + + a = a.transpose(-2, -3) + + max_a = torch.max(a, dim=-1, keepdim=True)[0] + exp_a = torch.exp(a - max_a) + exp_v = torch.einsum("...vhf,...qhv->...qhf", v_chunk, exp_a) + + maxes.append(max_a.detach().squeeze(-1)) + weights.append(torch.sum(exp_a, dim=-1)) + values.append(exp_v) + + chunk_max = torch.stack(maxes, dim=-3) + chunk_weights = torch.stack(weights, dim=-3) + chunk_values = torch.stack(values, dim=-4) + + global_max = torch.max(chunk_max, dim=-3, keepdim=True)[0] + max_diffs = torch.exp(chunk_max - global_max) + chunk_values *= max_diffs.unsqueeze(-1) + chunk_weights *= max_diffs + + all_values = torch.sum(chunk_values, dim=-4) + all_weights = torch.sum(chunk_weights.unsqueeze(-1), dim=-4) + + q_chunk_out = all_values / all_weights + + o[..., q_s: q_s + q_chunk_size, :, :] = q_chunk_out + + return o diff --git a/gafl/openfold/model/structure_module.py b/gafl/openfold/model/structure_module.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6ba1fe42b995b123a43095bc51a947999b102b --- /dev/null +++ b/gafl/openfold/model/structure_module.py @@ -0,0 +1,820 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from functools import reduce +import importlib +import math +import sys +from operator import mul + +import torch +import torch.nn as nn +from typing import Optional, Tuple, Sequence + +from openfold.model.primitives import Linear, LayerNorm, ipa_point_weights_init_ +from openfold.np.residue_constants import ( + restype_rigid_group_default_frame, + restype_atom14_to_rigid_group, + restype_atom14_mask, + restype_atom14_rigid_group_positions, +) +from openfold.utils.feats import ( + frames_and_literature_positions_to_atom14_pos, + torsion_angles_to_frames, +) +from openfold.utils.precision_utils import is_fp16_enabled +from openfold.utils.rigid_utils import Rotation, Rigid +from openfold.utils.tensor_utils import ( + dict_multimap, + permute_final_dims, + flatten_final_dims, +) + +# attn_core_inplace_cuda = importlib.import_module("attn_core_inplace_cuda") + + +class AngleResnetBlock(nn.Module): + def __init__(self, c_hidden): + """ + Args: + c_hidden: + Hidden channel dimension + """ + super(AngleResnetBlock, self).__init__() + + self.c_hidden = c_hidden + + self.linear_1 = Linear(self.c_hidden, self.c_hidden, init="relu") + self.linear_2 = Linear(self.c_hidden, self.c_hidden, init="final") + + self.relu = nn.ReLU() + + def forward(self, a: torch.Tensor) -> torch.Tensor: + + s_initial = a + + a = self.relu(a) + a = self.linear_1(a) + a = self.relu(a) + a = self.linear_2(a) + + return a + s_initial + + +class AngleResnet(nn.Module): + """ + Implements Algorithm 20, lines 11-14 + """ + + def __init__(self, c_in, c_hidden, no_blocks, no_angles, epsilon): + """ + Args: + c_in: + Input channel dimension + c_hidden: + Hidden channel dimension + no_blocks: + Number of resnet blocks + no_angles: + Number of torsion angles to generate + epsilon: + Small constant for normalization + """ + super(AngleResnet, self).__init__() + + self.c_in = c_in + self.c_hidden = c_hidden + self.no_blocks = no_blocks + self.no_angles = no_angles + self.eps = epsilon + + self.linear_in = Linear(self.c_in, self.c_hidden) + self.linear_initial = Linear(self.c_in, self.c_hidden) + + self.layers = nn.ModuleList() + for _ in range(self.no_blocks): + layer = AngleResnetBlock(c_hidden=self.c_hidden) + self.layers.append(layer) + + self.linear_out = Linear(self.c_hidden, self.no_angles * 2) + + self.relu = nn.ReLU() + + def forward( + self, s: torch.Tensor, s_initial: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + s: + [*, C_hidden] single embedding + s_initial: + [*, C_hidden] single embedding as of the start of the + StructureModule + Returns: + [*, no_angles, 2] predicted angles + """ + # NOTE: The ReLU's applied to the inputs are absent from the supplement + # pseudocode but present in the source. For maximal compatibility with + # the pretrained weights, I'm going with the source. + + # [*, C_hidden] + s_initial = self.relu(s_initial) + s_initial = self.linear_initial(s_initial) + s = self.relu(s) + s = self.linear_in(s) + s = s + s_initial + + for l in self.layers: + s = l(s) + + s = self.relu(s) + + # [*, no_angles * 2] + s = self.linear_out(s) + + # [*, no_angles, 2] + s = s.view(s.shape[:-1] + (-1, 2)) + + unnormalized_s = s + norm_denom = torch.sqrt( + torch.clamp( + torch.sum(s ** 2, dim=-1, keepdim=True), + min=self.eps, + ) + ) + s = s / norm_denom + + return unnormalized_s, s + + +class InvariantPointAttention(nn.Module): + """ + Implements Algorithm 22. + """ + def __init__( + self, + c_s: int, + c_z: int, + c_hidden: int, + no_heads: int, + no_qk_points: int, + no_v_points: int, + inf: float = 1e5, + eps: float = 1e-8, + ): + """ + Args: + c_s: + Single representation channel dimension + c_z: + Pair representation channel dimension + c_hidden: + Hidden channel dimension + no_heads: + Number of attention heads + no_qk_points: + Number of query/key points to generate + no_v_points: + Number of value points to generate + """ + super(InvariantPointAttention, self).__init__() + + self.c_s = c_s + self.c_z = c_z + self.c_hidden = c_hidden + self.no_heads = no_heads + self.no_qk_points = no_qk_points + self.no_v_points = no_v_points + self.inf = inf + self.eps = eps + + # These linear layers differ from their specifications in the + # supplement. There, they lack bias and use Glorot initialization. + # Here as in the official source, they have bias and use the default + # Lecun initialization. + hc = self.c_hidden * self.no_heads + self.linear_q = Linear(self.c_s, hc) + self.linear_kv = Linear(self.c_s, 2 * hc) + + hpq = self.no_heads * self.no_qk_points * 3 + self.linear_q_points = Linear(self.c_s, hpq) + + hpkv = self.no_heads * (self.no_qk_points + self.no_v_points) * 3 + self.linear_kv_points = Linear(self.c_s, hpkv) + + hpv = self.no_heads * self.no_v_points * 3 + + self.linear_b = Linear(self.c_z, self.no_heads) + + self.head_weights = nn.Parameter(torch.zeros((no_heads))) + ipa_point_weights_init_(self.head_weights) + + concat_out_dim = self.no_heads * ( + self.c_z + self.c_hidden + self.no_v_points * 4 + ) + self.linear_out = Linear(concat_out_dim, self.c_s, init="final") + + self.softmax = nn.Softmax(dim=-1) + self.softplus = nn.Softplus() + + def forward( + self, + s: torch.Tensor, + z: Optional[torch.Tensor], + r: Rigid, + mask: torch.Tensor, + inplace_safe: bool = False, + _offload_inference: bool = False, + _z_reference_list: Optional[Sequence[torch.Tensor]] = None, + ) -> torch.Tensor: + """ + Args: + s: + [*, N_res, C_s] single representation + z: + [*, N_res, N_res, C_z] pair representation + r: + [*, N_res] transformation object + mask: + [*, N_res] mask + Returns: + [*, N_res, C_s] single representation update + """ + if(_offload_inference and inplace_safe): + z = _z_reference_list + else: + z = [z] + + ####################################### + # Generate scalar and point activations + ####################################### + # [*, N_res, H * C_hidden] + q = self.linear_q(s) + kv = self.linear_kv(s) + + # [*, N_res, H, C_hidden] + q = q.view(q.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, 2 * C_hidden] + kv = kv.view(kv.shape[:-1] + (self.no_heads, -1)) + + # [*, N_res, H, C_hidden] + k, v = torch.split(kv, self.c_hidden, dim=-1) + + # [*, N_res, H * P_q * 3] + q_pts = self.linear_q_points(s) + + # This is kind of clunky, but it's how the original does it + # [*, N_res, H * P_q, 3] + q_pts = torch.split(q_pts, q_pts.shape[-1] // 3, dim=-1) + q_pts = torch.stack(q_pts, dim=-1) + q_pts = r[..., None].apply(q_pts) + + # [*, N_res, H, P_q, 3] + q_pts = q_pts.view( + q_pts.shape[:-2] + (self.no_heads, self.no_qk_points, 3) + ) + + # [*, N_res, H * (P_q + P_v) * 3] + kv_pts = self.linear_kv_points(s) + + # [*, N_res, H * (P_q + P_v), 3] + kv_pts = torch.split(kv_pts, kv_pts.shape[-1] // 3, dim=-1) + kv_pts = torch.stack(kv_pts, dim=-1) + kv_pts = r[..., None].apply(kv_pts) + + # [*, N_res, H, (P_q + P_v), 3] + kv_pts = kv_pts.view(kv_pts.shape[:-2] + (self.no_heads, -1, 3)) + + # [*, N_res, H, P_q/P_v, 3] + k_pts, v_pts = torch.split( + kv_pts, [self.no_qk_points, self.no_v_points], dim=-2 + ) + + ########################## + # Compute attention scores + ########################## + # [*, N_res, N_res, H] + b = self.linear_b(z[0]) + + if(_offload_inference): + assert(sys.getrefcount(z[0]) == 2) + z[0] = z[0].cpu() + + # [*, H, N_res, N_res] + if(is_fp16_enabled()): + with torch.cuda.amp.autocast(enabled=False): + a = torch.matmul( + permute_final_dims(q.float(), (1, 0, 2)), # [*, H, N_res, C_hidden] + permute_final_dims(k.float(), (1, 2, 0)), # [*, H, C_hidden, N_res] + ) + else: + a = torch.matmul( + permute_final_dims(q, (1, 0, 2)), # [*, H, N_res, C_hidden] + permute_final_dims(k, (1, 2, 0)), # [*, H, C_hidden, N_res] + ) + + a *= math.sqrt(1.0 / (3 * self.c_hidden)) + a += (math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))) + + # [*, N_res, N_res, H, P_q, 3] + pt_att = q_pts.unsqueeze(-4) - k_pts.unsqueeze(-5) + if(inplace_safe): + pt_att *= pt_att + else: + pt_att = pt_att ** 2 + + # [*, N_res, N_res, H, P_q] + pt_att = sum(torch.unbind(pt_att, dim=-1)) + head_weights = self.softplus(self.head_weights).view( + *((1,) * len(pt_att.shape[:-2]) + (-1, 1)) + ) + head_weights = head_weights * math.sqrt( + 1.0 / (3 * (self.no_qk_points * 9.0 / 2)) + ) + if(inplace_safe): + pt_att *= head_weights + else: + pt_att = pt_att * head_weights + + # [*, N_res, N_res, H] + pt_att = torch.sum(pt_att, dim=-1) * (-0.5) + # [*, N_res, N_res] + square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2) + square_mask = self.inf * (square_mask - 1) + + # [*, H, N_res, N_res] + pt_att = permute_final_dims(pt_att, (2, 0, 1)) + + if(inplace_safe): + a += pt_att + del pt_att + a += square_mask.unsqueeze(-3) + # in-place softmax + attn_core_inplace_cuda.forward_( + a, + reduce(mul, a.shape[:-1]), + a.shape[-1], + ) + else: + a = a + pt_att + a = a + square_mask.unsqueeze(-3) + a = self.softmax(a) + + ################ + # Compute output + ################ + # [*, N_res, H, C_hidden] + o = torch.matmul( + a, v.transpose(-2, -3).to(dtype=a.dtype) + ).transpose(-2, -3) + + # [*, N_res, H * C_hidden] + o = flatten_final_dims(o, 2) + + # [*, H, 3, N_res, P_v] + if(inplace_safe): + v_pts = permute_final_dims(v_pts, (1, 3, 0, 2)) + o_pt = [ + torch.matmul(a, v.to(a.dtype)) + for v in torch.unbind(v_pts, dim=-3) + ] + o_pt = torch.stack(o_pt, dim=-3) + else: + o_pt = torch.sum( + ( + a[..., None, :, :, None] + * permute_final_dims(v_pts, (1, 3, 0, 2))[..., None, :, :] + ), + dim=-2, + ) + + # [*, N_res, H, P_v, 3] + o_pt = permute_final_dims(o_pt, (2, 0, 3, 1)) + o_pt = r[..., None, None].invert_apply(o_pt) + + # [*, N_res, H * P_v] + o_pt_norm = flatten_final_dims( + torch.sqrt(torch.sum(o_pt ** 2, dim=-1) + self.eps), 2 + ) + + # [*, N_res, H * P_v, 3] + o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 3) + + if(_offload_inference): + z[0] = z[0].to(o_pt.device) + + # [*, N_res, H, C_z] + o_pair = torch.matmul(a.transpose(-2, -3), z[0].to(dtype=a.dtype)) + + # [*, N_res, H * C_z] + o_pair = flatten_final_dims(o_pair, 2) + + # [*, N_res, C_s] + s = self.linear_out( + torch.cat( + (o, *torch.unbind(o_pt, dim=-1), o_pt_norm, o_pair), dim=-1 + ).to(dtype=z[0].dtype) + ) + + return s + + +class BackboneUpdate(nn.Module): + """ + Implements part of Algorithm 23. + """ + + def __init__(self, c_s): + """ + Args: + c_s: + Single representation channel dimension + """ + super(BackboneUpdate, self).__init__() + + self.c_s = c_s + + self.linear = Linear(self.c_s, 6, init="final") + + def forward(self, s: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + [*, N_res, C_s] single representation + Returns: + [*, N_res, 6] update vector + """ + # [*, 6] + update = self.linear(s) + + return update + + +class StructureModuleTransitionLayer(nn.Module): + def __init__(self, c): + super(StructureModuleTransitionLayer, self).__init__() + + self.c = c + + self.linear_1 = Linear(self.c, self.c, init="relu") + self.linear_2 = Linear(self.c, self.c, init="relu") + self.linear_3 = Linear(self.c, self.c, init="final") + + self.relu = nn.ReLU() + + def forward(self, s): + s_initial = s + s = self.linear_1(s) + s = self.relu(s) + s = self.linear_2(s) + s = self.relu(s) + s = self.linear_3(s) + + s = s + s_initial + + return s + + +class StructureModuleTransition(nn.Module): + def __init__(self, c, num_layers, dropout_rate): + super(StructureModuleTransition, self).__init__() + + self.c = c + self.num_layers = num_layers + self.dropout_rate = dropout_rate + + self.layers = nn.ModuleList() + for _ in range(self.num_layers): + l = StructureModuleTransitionLayer(self.c) + self.layers.append(l) + + self.dropout = nn.Dropout(self.dropout_rate) + self.layer_norm = LayerNorm(self.c) + + def forward(self, s): + for l in self.layers: + s = l(s) + + s = self.dropout(s) + s = self.layer_norm(s) + + return s + + +class StructureModule(nn.Module): + def __init__( + self, + c_s, + c_z, + c_ipa, + c_resnet, + no_heads_ipa, + no_qk_points, + no_v_points, + dropout_rate, + no_blocks, + no_transition_layers, + no_resnet_blocks, + no_angles, + trans_scale_factor, + epsilon, + inf, + **kwargs, + ): + """ + Args: + c_s: + Single representation channel dimension + c_z: + Pair representation channel dimension + c_ipa: + IPA hidden channel dimension + c_resnet: + Angle resnet (Alg. 23 lines 11-14) hidden channel dimension + no_heads_ipa: + Number of IPA heads + no_qk_points: + Number of query/key points to generate during IPA + no_v_points: + Number of value points to generate during IPA + dropout_rate: + Dropout rate used throughout the layer + no_blocks: + Number of structure module blocks + no_transition_layers: + Number of layers in the single representation transition + (Alg. 23 lines 8-9) + no_resnet_blocks: + Number of blocks in the angle resnet + no_angles: + Number of angles to generate in the angle resnet + trans_scale_factor: + Scale of single representation transition hidden dimension + epsilon: + Small number used in angle resnet normalization + inf: + Large number used for attention masking + """ + super(StructureModule, self).__init__() + + self.c_s = c_s + self.c_z = c_z + self.c_ipa = c_ipa + self.c_resnet = c_resnet + self.no_heads_ipa = no_heads_ipa + self.no_qk_points = no_qk_points + self.no_v_points = no_v_points + self.dropout_rate = dropout_rate + self.no_blocks = no_blocks + self.no_transition_layers = no_transition_layers + self.no_resnet_blocks = no_resnet_blocks + self.no_angles = no_angles + self.trans_scale_factor = trans_scale_factor + self.epsilon = epsilon + self.inf = inf + + # Buffers to be lazily initialized later + # self.default_frames + # self.group_idx + # self.atom_mask + # self.lit_positions + + self.layer_norm_s = LayerNorm(self.c_s) + self.layer_norm_z = LayerNorm(self.c_z) + + self.linear_in = Linear(self.c_s, self.c_s) + + self.ipa = InvariantPointAttention( + self.c_s, + self.c_z, + self.c_ipa, + self.no_heads_ipa, + self.no_qk_points, + self.no_v_points, + inf=self.inf, + eps=self.epsilon, + ) + + self.ipa_dropout = nn.Dropout(self.dropout_rate) + self.layer_norm_ipa = LayerNorm(self.c_s) + + self.transition = StructureModuleTransition( + self.c_s, + self.no_transition_layers, + self.dropout_rate, + ) + + self.bb_update = BackboneUpdate(self.c_s) + + self.angle_resnet = AngleResnet( + self.c_s, + self.c_resnet, + self.no_resnet_blocks, + self.no_angles, + self.epsilon, + ) + + def forward( + self, + evoformer_output_dict, + aatype, + mask=None, + inplace_safe=False, + _offload_inference=False, + ): + """ + Args: + evoformer_output_dict: + Dictionary containing: + "single": + [*, N_res, C_s] single representation + "pair": + [*, N_res, N_res, C_z] pair representation + aatype: + [*, N_res] amino acid indices + mask: + Optional [*, N_res] sequence mask + Returns: + A dictionary of outputs + """ + s = evoformer_output_dict["single"] + + if mask is None: + # [*, N] + mask = s.new_ones(s.shape[:-1]) + + # [*, N, C_s] + s = self.layer_norm_s(s) + + # [*, N, N, C_z] + z = self.layer_norm_z(evoformer_output_dict["pair"]) + + z_reference_list = None + if(_offload_inference): + assert(sys.getrefcount(evoformer_output_dict["pair"]) == 2) + evoformer_output_dict["pair"] = evoformer_output_dict["pair"].cpu() + z_reference_list = [z] + z = None + + # [*, N, C_s] + s_initial = s + s = self.linear_in(s) + + # [*, N] + rigids = Rigid.identity( + s.shape[:-1], + s.dtype, + s.device, + self.training, + fmt="quat", + ) + outputs = [] + for i in range(self.no_blocks): + # [*, N, C_s] + s = s + self.ipa( + s, + z, + rigids, + mask, + inplace_safe=inplace_safe, + _offload_inference=_offload_inference, + _z_reference_list=z_reference_list + ) + s = self.ipa_dropout(s) + s = self.layer_norm_ipa(s) + s = self.transition(s) + + # [*, N] + rigids = rigids.compose_q_update_vec(self.bb_update(s)) + + # To hew as closely as possible to AlphaFold, we convert our + # quaternion-based transformations to rotation-matrix ones + # here + backb_to_global = Rigid( + Rotation( + rot_mats=rigids.get_rots().get_rot_mats(), + quats=None + ), + rigids.get_trans(), + ) + + backb_to_global = backb_to_global.scale_translation( + self.trans_scale_factor + ) + + # [*, N, 7, 2] + unnormalized_angles, angles = self.angle_resnet(s, s_initial) + + all_frames_to_global = self.torsion_angles_to_frames( + backb_to_global, + angles, + aatype, + ) + + pred_xyz = self.frames_and_literature_positions_to_atom14_pos( + all_frames_to_global, + aatype, + ) + + scaled_rigids = rigids.scale_translation(self.trans_scale_factor) + + preds = { + "frames": scaled_rigids.to_tensor_7(), + "sidechain_frames": all_frames_to_global.to_tensor_4x4(), + "unnormalized_angles": unnormalized_angles, + "angles": angles, + "positions": pred_xyz, + "states": s, + } + + outputs.append(preds) + + rigids = rigids.stop_rot_gradient() + + del z, z_reference_list + + if(_offload_inference): + evoformer_output_dict["pair"] = ( + evoformer_output_dict["pair"].to(s.device) + ) + + outputs = dict_multimap(torch.stack, outputs) + outputs["single"] = s + + return outputs + + def _init_residue_constants(self, float_dtype, device): + if not hasattr(self, "default_frames"): + self.register_buffer( + "default_frames", + torch.tensor( + restype_rigid_group_default_frame, + dtype=float_dtype, + device=device, + requires_grad=False, + ), + persistent=False, + ) + if not hasattr(self, "group_idx"): + self.register_buffer( + "group_idx", + torch.tensor( + restype_atom14_to_rigid_group, + device=device, + requires_grad=False, + ), + persistent=False, + ) + if not hasattr(self, "atom_mask"): + self.register_buffer( + "atom_mask", + torch.tensor( + restype_atom14_mask, + dtype=float_dtype, + device=device, + requires_grad=False, + ), + persistent=False, + ) + if not hasattr(self, "lit_positions"): + self.register_buffer( + "lit_positions", + torch.tensor( + restype_atom14_rigid_group_positions, + dtype=float_dtype, + device=device, + requires_grad=False, + ), + persistent=False, + ) + + def torsion_angles_to_frames(self, r, alpha, f): + # Lazily initialize the residue constants on the correct device + self._init_residue_constants(alpha.dtype, alpha.device) + # Separated purely to make testing less annoying + return torsion_angles_to_frames(r, alpha, f, self.default_frames) + + def frames_and_literature_positions_to_atom14_pos( + self, r, f # [*, N, 8] # [*, N] + ): + # Lazily initialize the residue constants on the correct device + self._init_residue_constants(r.get_rots().dtype, r.get_rots().device) + return frames_and_literature_positions_to_atom14_pos( + r, + f, + self.default_frames, + self.group_idx, + self.atom_mask, + self.lit_positions, + ) diff --git a/gafl/openfold/model/template.py b/gafl/openfold/model/template.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e1fd95bd0fa073b55be7714a794f14ae0234d0 --- /dev/null +++ b/gafl/openfold/model/template.py @@ -0,0 +1,333 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from functools import partial +import math +from typing import Optional, List + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear, LayerNorm, Attention +from openfold.model.dropout import ( + DropoutRowwise, + DropoutColumnwise, +) +from openfold.model.pair_transition import PairTransition +from openfold.model.triangular_attention import ( + TriangleAttentionStartingNode, + TriangleAttentionEndingNode, +) +from openfold.model.triangular_multiplicative_update import ( + TriangleMultiplicationOutgoing, + TriangleMultiplicationIncoming, +) +from openfold.utils.checkpointing import checkpoint_blocks +from openfold.utils.tensor_utils import ( + chunk_layer, + permute_final_dims, + flatten_final_dims, +) + + +class TemplatePointwiseAttention(nn.Module): + """ + Implements Algorithm 17. + """ + def __init__(self, c_t, c_z, c_hidden, no_heads, inf, **kwargs): + """ + Args: + c_t: + Template embedding channel dimension + c_z: + Pair embedding channel dimension + c_hidden: + Hidden channel dimension + """ + super(TemplatePointwiseAttention, self).__init__() + + self.c_t = c_t + self.c_z = c_z + self.c_hidden = c_hidden + self.no_heads = no_heads + self.inf = inf + + self.mha = Attention( + self.c_z, + self.c_t, + self.c_t, + self.c_hidden, + self.no_heads, + gating=False, + ) + + def _chunk(self, + z: torch.Tensor, + t: torch.Tensor, + biases: List[torch.Tensor], + chunk_size: int, + ) -> torch.Tensor: + mha_inputs = { + "q_x": z, + "kv_x": t, + "biases": biases, + } + return chunk_layer( + self.mha, + mha_inputs, + chunk_size=chunk_size, + no_batch_dims=len(z.shape[:-2]), + ) + + + def forward(self, + t: torch.Tensor, + z: torch.Tensor, + template_mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None + ) -> torch.Tensor: + """ + Args: + t: + [*, N_templ, N_res, N_res, C_t] template embedding + z: + [*, N_res, N_res, C_t] pair embedding + template_mask: + [*, N_templ] template mask + Returns: + [*, N_res, N_res, C_z] pair embedding update + """ + if template_mask is None: + template_mask = t.new_ones(t.shape[:-3]) + + bias = self.inf * (template_mask[..., None, None, None, None, :] - 1) + + # [*, N_res, N_res, 1, C_z] + z = z.unsqueeze(-2) + + # [*, N_res, N_res, N_temp, C_t] + t = permute_final_dims(t, (1, 2, 0, 3)) + + # [*, N_res, N_res, 1, C_z] + biases = [bias] + if chunk_size is not None: + z = self._chunk(z, t, biases, chunk_size) + else: + z = self.mha(q_x=z, kv_x=t, biases=biases) + + # [*, N_res, N_res, C_z] + z = z.squeeze(-2) + + return z + + +class TemplatePairStackBlock(nn.Module): + def __init__( + self, + c_t: int, + c_hidden_tri_att: int, + c_hidden_tri_mul: int, + no_heads: int, + pair_transition_n: int, + dropout_rate: float, + inf: float, + **kwargs, + ): + super(TemplatePairStackBlock, self).__init__() + + self.c_t = c_t + self.c_hidden_tri_att = c_hidden_tri_att + self.c_hidden_tri_mul = c_hidden_tri_mul + self.no_heads = no_heads + self.pair_transition_n = pair_transition_n + self.dropout_rate = dropout_rate + self.inf = inf + + self.dropout_row = DropoutRowwise(self.dropout_rate) + self.dropout_col = DropoutColumnwise(self.dropout_rate) + + self.tri_att_start = TriangleAttentionStartingNode( + self.c_t, + self.c_hidden_tri_att, + self.no_heads, + inf=inf, + ) + self.tri_att_end = TriangleAttentionEndingNode( + self.c_t, + self.c_hidden_tri_att, + self.no_heads, + inf=inf, + ) + + self.tri_mul_out = TriangleMultiplicationOutgoing( + self.c_t, + self.c_hidden_tri_mul, + ) + self.tri_mul_in = TriangleMultiplicationIncoming( + self.c_t, + self.c_hidden_tri_mul, + ) + + self.pair_transition = PairTransition( + self.c_t, + self.pair_transition_n, + ) + + def forward(self, + z: torch.Tensor, + mask: torch.Tensor, + chunk_size: Optional[int] = None, + _mask_trans: bool = True + ): + single_templates = [ + t.unsqueeze(-4) for t in torch.unbind(z, dim=-4) + ] + single_templates_masks = [ + m.unsqueeze(-3) for m in torch.unbind(mask, dim=-3) + ] + for i in range(len(single_templates)): + single = single_templates[i] + single_mask = single_templates_masks[i] + + single = single + self.dropout_row( + self.tri_att_start( + single, + chunk_size=chunk_size, + mask=single_mask + ) + ) + single = single + self.dropout_col( + self.tri_att_end( + single, + chunk_size=chunk_size, + mask=single_mask + ) + ) + single = single + self.dropout_row( + self.tri_mul_out( + single, + mask=single_mask + ) + ) + single = single + self.dropout_row( + self.tri_mul_in( + single, + mask=single_mask + ) + ) + single = single + self.pair_transition( + single, + mask=single_mask if _mask_trans else None, + chunk_size=chunk_size, + ) + + single_templates[i] = single + + z = torch.cat(single_templates, dim=-4) + + return z + + +class TemplatePairStack(nn.Module): + """ + Implements Algorithm 16. + """ + def __init__( + self, + c_t, + c_hidden_tri_att, + c_hidden_tri_mul, + no_blocks, + no_heads, + pair_transition_n, + dropout_rate, + blocks_per_ckpt, + inf=1e9, + **kwargs, + ): + """ + Args: + c_t: + Template embedding channel dimension + c_hidden_tri_att: + Per-head hidden dimension for triangular attention + c_hidden_tri_att: + Hidden dimension for triangular multiplication + no_blocks: + Number of blocks in the stack + pair_transition_n: + Scale of pair transition (Alg. 15) hidden dimension + dropout_rate: + Dropout rate used throughout the stack + blocks_per_ckpt: + Number of blocks per activation checkpoint. None disables + activation checkpointing + """ + super(TemplatePairStack, self).__init__() + + self.blocks_per_ckpt = blocks_per_ckpt + + self.blocks = nn.ModuleList() + for _ in range(no_blocks): + block = TemplatePairStackBlock( + c_t=c_t, + c_hidden_tri_att=c_hidden_tri_att, + c_hidden_tri_mul=c_hidden_tri_mul, + no_heads=no_heads, + pair_transition_n=pair_transition_n, + dropout_rate=dropout_rate, + inf=inf, + ) + self.blocks.append(block) + + self.layer_norm = LayerNorm(c_t) + + def forward( + self, + t: torch.tensor, + mask: torch.tensor, + chunk_size: int, + _mask_trans: bool = True, + ): + """ + Args: + t: + [*, N_templ, N_res, N_res, C_t] template embedding + mask: + [*, N_templ, N_res, N_res] mask + Returns: + [*, N_templ, N_res, N_res, C_t] template embedding update + """ + if(mask.shape[-3] == 1): + expand_idx = list(mask.shape) + expand_idx[-3] = t.shape[-4] + mask = mask.expand(*expand_idx) + + t, = checkpoint_blocks( + blocks=[ + partial( + b, + mask=mask, + chunk_size=chunk_size, + _mask_trans=_mask_trans, + ) + for b in self.blocks + ], + args=(t,), + blocks_per_ckpt=self.blocks_per_ckpt if self.training else None, + ) + + t = self.layer_norm(t) + + return t diff --git a/gafl/openfold/model/torchscript.py b/gafl/openfold/model/torchscript.py new file mode 100644 index 0000000000000000000000000000000000000000..cac7e6725b04f9383bd27cb5599b4e5172462de5 --- /dev/null +++ b/gafl/openfold/model/torchscript.py @@ -0,0 +1,215 @@ +# Copyright 2021 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn as nn + +from openfold.model.dropout import ( + DropoutRowwise, + DropoutColumnwise, +) +from openfold.model.evoformer import ( + EvoformerBlock, + EvoformerStack, +) +from openfold.model.outer_product_mean import OuterProductMean +from openfold.model.msa import ( + MSARowAttentionWithPairBias, + MSAColumnAttention, + MSAColumnGlobalAttention, +) +from openfold.model.pair_transition import PairTransition +from openfold.model.primitives import Attention, GlobalAttention +from openfold.model.structure_module import ( + InvariantPointAttention, + BackboneUpdate, +) +from openfold.model.template import TemplatePairStackBlock +from openfold.model.triangular_attention import ( + TriangleAttentionStartingNode, + TriangleAttentionEndingNode, +) +from openfold.model.triangular_multiplicative_update import ( + TriangleMultiplicationOutgoing, + TriangleMultiplicationIncoming, +) + + +def script_preset_(model: torch.nn.Module): + """ + TorchScript a handful of low-level but frequently used submodule types + that are known to be scriptable. + + Args: + model: + A torch.nn.Module. It should contain at least some modules from + this repository, or this function won't do anything. + """ + script_submodules_( + model, + [ + nn.Dropout, + Attention, + GlobalAttention, + EvoformerBlock, + #TemplatePairStackBlock, + ], + attempt_trace=False, + batch_dims=None, + ) + + +def _get_module_device(module: torch.nn.Module) -> torch.device: + """ + Fetches the device of a module, assuming that all of the module's + parameters reside on a single device + + Args: + module: A torch.nn.Module + Returns: + The module's device + """ + return next(module.parameters()).device + + +def _trace_module(module, batch_dims=None): + if(batch_dims is None): + batch_dims = () + + # Stand-in values + n_seq = 10 + n_res = 10 + + device = _get_module_device(module) + + def msa(channel_dim): + return torch.rand( + (*batch_dims, n_seq, n_res, channel_dim), + device=device, + ) + + def pair(channel_dim): + return torch.rand( + (*batch_dims, n_res, n_res, channel_dim), + device=device, + ) + + if(isinstance(module, MSARowAttentionWithPairBias)): + inputs = { + "forward": ( + msa(module.c_in), # m + pair(module.c_z), # z + torch.randint( + 0, 2, + (*batch_dims, n_seq, n_res) + ), # mask + ), + } + elif(isinstance(module, MSAColumnAttention)): + inputs = { + "forward": ( + msa(module.c_in), # m + torch.randint( + 0, 2, + (*batch_dims, n_seq, n_res) + ), # mask + ), + } + elif(isinstance(module, OuterProductMean)): + inputs = { + "forward": ( + msa(module.c_m), + torch.randint( + 0, 2, + (*batch_dims, n_seq, n_res) + ) + ) + } + else: + raise TypeError( + f"tracing is not supported for modules of type {type(module)}" + ) + + return torch.jit.trace_module(module, inputs) + + +def _script_submodules_helper_( + model, + types, + attempt_trace, + to_trace, +): + for name, child in model.named_children(): + if(types is None or any(isinstance(child, t) for t in types)): + try: + scripted = torch.jit.script(child) + setattr(model, name, scripted) + continue + except (RuntimeError, torch.jit.frontend.NotSupportedError) as e: + if(attempt_trace): + to_trace.add(type(child)) + else: + raise e + + _script_submodules_helper_(child, types, attempt_trace, to_trace) + + +def _trace_submodules_( + model, + types, + batch_dims=None, +): + for name, child in model.named_children(): + if(any(isinstance(child, t) for t in types)): + traced = _trace_module(child, batch_dims=batch_dims) + setattr(model, name, traced) + else: + _trace_submodules_(child, types, batch_dims=batch_dims) + + +def script_submodules_( + model: nn.Module, + types: Optional[Sequence[type]] = None, + attempt_trace: Optional[bool] = True, + batch_dims: Optional[Tuple[int]] = None, +): + """ + Convert all submodules whose types match one of those in the input + list to recursively scripted equivalents in place. To script the entire + model, just call torch.jit.script on it directly. + + When types is None, all submodules are scripted. + + Args: + model: + A torch.nn.Module + types: + A list of types of submodules to script + attempt_trace: + Whether to attempt to trace specified modules if scripting + fails. Recall that tracing eliminates all conditional + logic---with great tracing comes the mild responsibility of + having to remember to ensure that the modules in question + perform the same computations no matter what. + """ + to_trace = set() + + # Aggressively script as much as possible first... + _script_submodules_helper_(model, types, attempt_trace, to_trace) + + # ... and then trace stragglers. + if(attempt_trace and len(to_trace) > 0): + _trace_submodules_(model, to_trace, batch_dims=batch_dims) diff --git a/gafl/openfold/model/triangular_attention.py b/gafl/openfold/model/triangular_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..91fa2bb62a110825cc584eb2aff02e753ad3b307 --- /dev/null +++ b/gafl/openfold/model/triangular_attention.py @@ -0,0 +1,139 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partialmethod, partial +import math +from typing import Optional, List + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear, LayerNorm, Attention +from openfold.utils.tensor_utils import ( + chunk_layer, + permute_final_dims, + flatten_final_dims, +) + + +class TriangleAttention(nn.Module): + def __init__( + self, c_in, c_hidden, no_heads, starting, inf=1e9 + ): + """ + Args: + c_in: + Input channel dimension + c_hidden: + Overall hidden channel dimension (not per-head) + no_heads: + Number of attention heads + """ + super(TriangleAttention, self).__init__() + + self.c_in = c_in + self.c_hidden = c_hidden + self.no_heads = no_heads + self.starting = starting + self.inf = inf + + self.layer_norm = LayerNorm(self.c_in) + + self.linear = Linear(c_in, self.no_heads, bias=False, init="normal") + + self.mha = Attention( + self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads + ) + + @torch.jit.ignore + def _chunk(self, + x: torch.Tensor, + biases: List[torch.Tensor], + chunk_size: int, + ) -> torch.Tensor: + mha_inputs = { + "q_x": x, + "kv_x": x, + "biases": biases, + } + return chunk_layer( + partial(self.mha), + mha_inputs, + chunk_size=chunk_size, + no_batch_dims=len(x.shape[:-2]), + ) + + def forward(self, + x: torch.Tensor, + mask: Optional[torch.Tensor] = None, + chunk_size: Optional[int] = None + ) -> torch.Tensor: + """ + Args: + x: + [*, I, J, C_in] input tensor (e.g. the pair representation) + Returns: + [*, I, J, C_in] output tensor + """ + if mask is None: + # [*, I, J] + mask = x.new_ones( + x.shape[:-1], + ) + + # Shape annotations assume self.starting. Else, I and J are flipped + if not self.starting: + x = x.transpose(-2, -3) + mask = mask.transpose(-1, -2) + + # [*, I, J, C_in] + x = self.layer_norm(x) + + # [*, I, 1, 1, J] + mask_bias = (self.inf * (mask - 1))[..., :, None, None, :] + + # [*, H, I, J] + triangle_bias = permute_final_dims(self.linear(x), (2, 0, 1)) + + # [*, 1, H, I, J] + triangle_bias = triangle_bias.unsqueeze(-4) + + biases = [mask_bias, triangle_bias] + + if chunk_size is not None: + x = self._chunk(x, biases, chunk_size) + else: + x = self.mha(q_x=x, kv_x=x, biases=biases) + + if not self.starting: + x = x.transpose(-2, -3) + + return x + + +class TriangleAttentionStartingNode(TriangleAttention): + """ + Implements Algorithm 13. + """ + + __init__ = partialmethod(TriangleAttention.__init__, starting=True) + + +class TriangleAttentionEndingNode(TriangleAttention): + """ + Implements Algorithm 14. + """ + + __init__ = partialmethod(TriangleAttention.__init__, starting=False) diff --git a/gafl/openfold/model/triangular_multiplicative_update.py b/gafl/openfold/model/triangular_multiplicative_update.py new file mode 100644 index 0000000000000000000000000000000000000000..2edd24f6f8ccab7e73e577ddc2aaa6d2443757ed --- /dev/null +++ b/gafl/openfold/model/triangular_multiplicative_update.py @@ -0,0 +1,127 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partialmethod +from typing import Optional + +import torch +import torch.nn as nn + +from openfold.model.primitives import Linear, LayerNorm +from openfold.utils.tensor_utils import permute_final_dims + + +class TriangleMultiplicativeUpdate(nn.Module): + """ + Implements Algorithms 11 and 12. + """ + def __init__(self, c_z, c_hidden, _outgoing=True): + """ + Args: + c_z: + Input channel dimension + c: + Hidden channel dimension + """ + super(TriangleMultiplicativeUpdate, self).__init__() + self.c_z = c_z + self.c_hidden = c_hidden + self._outgoing = _outgoing + + self.linear_a_p = Linear(self.c_z, self.c_hidden) + self.linear_a_g = Linear(self.c_z, self.c_hidden, init="gating") + self.linear_b_p = Linear(self.c_z, self.c_hidden) + self.linear_b_g = Linear(self.c_z, self.c_hidden, init="gating") + self.linear_g = Linear(self.c_z, self.c_z, init="gating") + self.linear_z = Linear(self.c_hidden, self.c_z, init="final") + + self.layer_norm_in = LayerNorm(self.c_z) + self.layer_norm_out = LayerNorm(self.c_hidden) + + self.sigmoid = nn.Sigmoid() + + def _combine_projections(self, + a: torch.Tensor, + b: torch.Tensor, + ) -> torch.Tensor: + raise NotImplementedError("This method needs to be overridden") + + def forward(self, + z: torch.Tensor, + mask: Optional[torch.Tensor] = None + ) -> torch.Tensor: + """ + Args: + x: + [*, N_res, N_res, C_z] input tensor + mask: + [*, N_res, N_res] input mask + Returns: + [*, N_res, N_res, C_z] output tensor + """ + if mask is None: + mask = z.new_ones(z.shape[:-1]) + + mask = mask.unsqueeze(-1) + + z = self.layer_norm_in(z) + a = self.linear_a_p(z) * self.sigmoid(self.linear_a_g(z)) + a = a * mask + b = self.linear_b_p(z) * self.sigmoid(self.linear_b_g(z)) + b = b * mask + x = self._combine_projections(a, b) + x = self.layer_norm_out(x) + x = self.linear_z(x) + g = self.sigmoid(self.linear_g(z)) + z = x * g + + return z + + +class TriangleMultiplicationOutgoing(TriangleMultiplicativeUpdate): + """ + Implements Algorithm 11. + """ + def _combine_projections(self, + a: torch.Tensor, # [*, N_i, N_k, C] + b: torch.Tensor, # [*, N_j, N_k, C] + ): + # [*, C, N_i, N_j] + p = torch.matmul( + permute_final_dims(a, (2, 0, 1)), + permute_final_dims(b, (2, 1, 0)), + ) + + # [*, N_i, N_j, C] + return permute_final_dims(p, (1, 2, 0)) + + +class TriangleMultiplicationIncoming(TriangleMultiplicativeUpdate): + """ + Implements Algorithm 12. + """ + def _combine_projections(self, + a: torch.Tensor, # [*, N_k, N_i, C] + b: torch.Tensor, # [*, N_k, N_j, C] + ): + # [*, C, N_i, N_j] + p = torch.matmul( + permute_final_dims(a, (2, 1, 0)), + permute_final_dims(b, (2, 0, 1)), + ) + + # [*, N_i, N_j, C] + return permute_final_dims(p, (1, 2, 0)) + diff --git a/gafl/openfold/np/__init__.py b/gafl/openfold/np/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25d1a5ba4be7300076d6f44af1541a33ca9e4ab1 --- /dev/null +++ b/gafl/openfold/np/__init__.py @@ -0,0 +1,16 @@ +import os +import glob +import importlib as importlib + +_files = glob.glob(os.path.join(os.path.dirname(__file__), "*.py")) +__all__ = [ + os.path.basename(f)[:-3] + for f in _files + if os.path.isfile(f) and not f.endswith("__init__.py") +] +_modules = [(m, importlib.import_module("." + m, __name__)) for m in __all__] +for _m in _modules: + globals()[_m[0]] = _m[1] + +# Avoid needlessly cluttering the global namespace +del _files, _m, _modules diff --git a/gafl/openfold/np/__pycache__/__init__.cpython-310.pyc b/gafl/openfold/np/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0e7bb3fc6fef3358b97eb750b38868b1f2698ae Binary files /dev/null and b/gafl/openfold/np/__pycache__/__init__.cpython-310.pyc differ diff --git a/gafl/openfold/np/__pycache__/__init__.cpython-311.pyc b/gafl/openfold/np/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d103afb308bf9f8c4e0992d54b13c685e1fbc84a Binary files /dev/null and b/gafl/openfold/np/__pycache__/__init__.cpython-311.pyc differ diff --git a/gafl/openfold/np/__pycache__/protein.cpython-310.pyc b/gafl/openfold/np/__pycache__/protein.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6e51596afc59ec58904d908fe26df8776f0f33e Binary files /dev/null and b/gafl/openfold/np/__pycache__/protein.cpython-310.pyc differ diff --git a/gafl/openfold/np/__pycache__/protein.cpython-311.pyc b/gafl/openfold/np/__pycache__/protein.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bb709db30f1c531ac9ba5ea9d45e0ad89f9f20b Binary files /dev/null and b/gafl/openfold/np/__pycache__/protein.cpython-311.pyc differ diff --git a/gafl/openfold/np/__pycache__/residue_constants.cpython-310.pyc b/gafl/openfold/np/__pycache__/residue_constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8957e9e6de65d68abfa6b4ec87baadd16ac950c Binary files /dev/null and b/gafl/openfold/np/__pycache__/residue_constants.cpython-310.pyc differ diff --git a/gafl/openfold/np/__pycache__/residue_constants.cpython-311.pyc b/gafl/openfold/np/__pycache__/residue_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4658a210a8a580eb1e9aa47c7911e722337caff6 Binary files /dev/null and b/gafl/openfold/np/__pycache__/residue_constants.cpython-311.pyc differ diff --git a/gafl/openfold/np/protein.py b/gafl/openfold/np/protein.py new file mode 100644 index 0000000000000000000000000000000000000000..75748b27d768d7765f1823c3eada5f7bcd0e4099 --- /dev/null +++ b/gafl/openfold/np/protein.py @@ -0,0 +1,438 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Protein data type.""" +import dataclasses +import io +from typing import Any, Sequence, Mapping, Optional +import re +import string + +from openfold.np import residue_constants +from Bio.PDB import PDBParser +import numpy as np + + +FeatureDict = Mapping[str, np.ndarray] +ModelOutput = Mapping[str, Any] # Is a nested dict. +PICO_TO_ANGSTROM = 0.01 + +@dataclasses.dataclass(frozen=True) +class Protein: + """Protein structure representation.""" + + # Cartesian coordinates of atoms in angstroms. The atom types correspond to + # residue_constants.atom_types, i.e. the first three are N, CA, CB. + atom_positions: np.ndarray # [num_res, num_atom_type, 3] + + # Amino-acid type for each residue represented as an integer between 0 and + # 20, where 20 is 'X'. + aatype: np.ndarray # [num_res] + + # Binary float mask to indicate presence of a particular atom. 1.0 if an atom + # is present and 0.0 if not. This should be used for loss masking. + atom_mask: np.ndarray # [num_res, num_atom_type] + + # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. + residue_index: np.ndarray # [num_res] + + # B-factors, or temperature factors, of each residue (in sq. angstroms units), + # representing the displacement of the residue from its ground truth mean + # value. + b_factors: np.ndarray # [num_res, num_atom_type] + + # Chain indices for multi-chain predictions + chain_index: Optional[np.ndarray] = None + + # Optional remark about the protein. Included as a comment in output PDB + # files + remark: Optional[str] = None + + # Templates used to generate this protein (prediction-only) + parents: Optional[Sequence[str]] = None + + # Chain corresponding to each parent + parents_chain_index: Optional[Sequence[int]] = None + + +def from_pdb_string(pdb_str: str, chain_id: Optional[str] = None) -> Protein: + """Takes a PDB string and constructs a Protein object. + + WARNING: All non-standard residue types will be converted into UNK. All + non-standard atoms will be ignored. + + Args: + pdb_str: The contents of the pdb file + chain_id: If None, then the pdb file must contain a single chain (which + will be parsed). If chain_id is specified (e.g. A), then only that chain + is parsed. + + Returns: + A new `Protein` parsed from the pdb contents. + """ + pdb_fh = io.StringIO(pdb_str) + parser = PDBParser(QUIET=True) + structure = parser.get_structure("none", pdb_fh) + models = list(structure.get_models()) + if len(models) != 1: + raise ValueError( + f"Only single model PDBs are supported. Found {len(models)} models." + ) + model = models[0] + + atom_positions = [] + aatype = [] + atom_mask = [] + residue_index = [] + chain_ids = [] + b_factors = [] + + for chain in model: + if(chain_id is not None and chain.id != chain_id): + continue + for res in chain: + if res.id[2] != " ": + raise ValueError( + f"PDB contains an insertion code at chain {chain.id} and residue " + f"index {res.id[1]}. These are not supported." + ) + res_shortname = residue_constants.restype_3to1.get(res.resname, "X") + restype_idx = residue_constants.restype_order.get( + res_shortname, residue_constants.restype_num + ) + pos = np.zeros((residue_constants.atom_type_num, 3)) + mask = np.zeros((residue_constants.atom_type_num,)) + res_b_factors = np.zeros((residue_constants.atom_type_num,)) + for atom in res: + if atom.name not in residue_constants.atom_types: + continue + pos[residue_constants.atom_order[atom.name]] = atom.coord + mask[residue_constants.atom_order[atom.name]] = 1.0 + res_b_factors[ + residue_constants.atom_order[atom.name] + ] = atom.bfactor + if np.sum(mask) < 0.5: + # If no known atom positions are reported for the residue then skip it. + continue + aatype.append(restype_idx) + atom_positions.append(pos) + atom_mask.append(mask) + residue_index.append(res.id[1]) + chain_ids.append(chain.id) + b_factors.append(res_b_factors) + + parents = None + parents_chain_index = None + if("PARENT" in pdb_str): + parents = [] + parents_chain_index = [] + chain_id = 0 + for l in pdb_str.split("\n"): + if("PARENT" in l): + if(not "N/A" in l): + parent_names = l.split()[1:] + parents.extend(parent_names) + parents_chain_index.extend([ + chain_id for _ in parent_names + ]) + chain_id += 1 + + unique_chain_ids = np.unique(chain_ids) + chain_id_mapping = {cid: n for n, cid in enumerate(string.ascii_uppercase)} + chain_index = np.array([chain_id_mapping[cid] for cid in chain_ids]) + + return Protein( + atom_positions=np.array(atom_positions), + atom_mask=np.array(atom_mask), + aatype=np.array(aatype), + residue_index=np.array(residue_index), + chain_index=chain_index, + b_factors=np.array(b_factors), + parents=parents, + parents_chain_index=parents_chain_index, + ) + + +def from_proteinnet_string(proteinnet_str: str) -> Protein: + tag_re = r'(\[[A-Z]+\]\n)' + tags = [ + tag.strip() for tag in re.split(tag_re, proteinnet_str) if len(tag) > 0 + ] + groups = zip(tags[0::2], [l.split('\n') for l in tags[1::2]]) + + atoms = ['N', 'CA', 'C'] + aatype = None + atom_positions = None + atom_mask = None + for g in groups: + if("[PRIMARY]" == g[0]): + seq = g[1][0].strip() + for i in range(len(seq)): + if(seq[i] not in residue_constants.restypes): + seq[i] = 'X' + aatype = np.array([ + residue_constants.restype_order.get( + res_symbol, residue_constants.restype_num + ) for res_symbol in seq + ]) + elif("[TERTIARY]" == g[0]): + tertiary = [] + for axis in range(3): + tertiary.append(list(map(float, g[1][axis].split()))) + tertiary_np = np.array(tertiary) + atom_positions = np.zeros( + (len(tertiary[0])//3, residue_constants.atom_type_num, 3) + ).astype(np.float32) + for i, atom in enumerate(atoms): + atom_positions[:, residue_constants.atom_order[atom], :] = ( + np.transpose(tertiary_np[:, i::3]) + ) + atom_positions *= PICO_TO_ANGSTROM + elif("[MASK]" == g[0]): + mask = np.array(list(map({'-': 0, '+': 1}.get, g[1][0].strip()))) + atom_mask = np.zeros( + (len(mask), residue_constants.atom_type_num,) + ).astype(np.float32) + for i, atom in enumerate(atoms): + atom_mask[:, residue_constants.atom_order[atom]] = 1 + atom_mask *= mask[..., None] + + return Protein( + atom_positions=atom_positions, + atom_mask=atom_mask, + aatype=aatype, + residue_index=np.arange(len(aatype)), + b_factors=None, + ) + + +def get_pdb_headers(prot: Protein, chain_id: int = 0) -> Sequence[str]: + pdb_headers = [] + + remark = prot.remark + if(remark is not None): + pdb_headers.append(f"REMARK {remark}") + + parents = prot.parents + parents_chain_index = prot.parents_chain_index + if(parents_chain_index is not None): + parents = [ + p for i, p in zip(parents_chain_index, parents) if i == chain_id + ] + + if(parents is None or len(parents) == 0): + parents = ["N/A"] + + pdb_headers.append(f"PARENT {' '.join(parents)}") + + return pdb_headers + + +def add_pdb_headers(prot: Protein, pdb_str: str) -> str: + """ Add pdb headers to an existing PDB string. Useful during multi-chain + recycling + """ + out_pdb_lines = [] + lines = pdb_str.split('\n') + + remark = prot.remark + if(remark is not None): + out_pdb_lines.append(f"REMARK {remark}") + + parents_per_chain = None + if(prot.parents is not None and len(prot.parents) > 0): + parents_per_chain = [] + if(prot.parents_chain_index is not None): + cur_chain = prot.parents_chain_index[0] + parent_dict = {} + for p, i in zip(prot.parents, prot.parents_chain_index): + parent_dict.setdefault(str(i), []) + parent_dict[str(i)].append(p) + + max_idx = max([int(chain_idx) for chain_idx in parent_dict]) + for i in range(max_idx + 1): + chain_parents = parent_dict.get(str(i), ["N/A"]) + parents_per_chain.append(chain_parents) + else: + parents_per_chain.append(prot.parents) + else: + parents_per_chain = [["N/A"]] + + make_parent_line = lambda p: f"PARENT {' '.join(p)}" + + out_pdb_lines.append(make_parent_line(parents_per_chain[0])) + + chain_counter = 0 + for i, l in enumerate(lines): + if("PARENT" not in l and "REMARK" not in l): + out_pdb_lines.append(l) + if("TER" in l and not "END" in lines[i + 1]): + chain_counter += 1 + if(not chain_counter >= len(parents_per_chain)): + chain_parents = parents_per_chain[chain_counter] + else: + chain_parents = ["N/A"] + + out_pdb_lines.append(make_parent_line(chain_parents)) + + return '\n'.join(out_pdb_lines) + + +def to_pdb(prot: Protein) -> str: + """Converts a `Protein` instance to a PDB string. + + Args: + prot: The protein to convert to PDB. + + Returns: + PDB string. + """ + restypes = residue_constants.restypes + ["X"] + res_1to3 = lambda r: residue_constants.restype_1to3.get(restypes[r], "UNK") + atom_types = residue_constants.atom_types + + pdb_lines = [] + + atom_mask = prot.atom_mask + aatype = prot.aatype + atom_positions = prot.atom_positions + residue_index = prot.residue_index.astype(int) + b_factors = prot.b_factors + chain_index = prot.chain_index + + if np.any(aatype > residue_constants.restype_num): + raise ValueError("Invalid aatypes.") + + headers = get_pdb_headers(prot) + if(len(headers) > 0): + pdb_lines.extend(headers) + + n = aatype.shape[0] + atom_index = 1 + prev_chain_index = 0 + chain_tags = string.ascii_uppercase + # Add all atom sites. + for i in range(n): + res_name_3 = res_1to3(aatype[i]) + for atom_name, pos, mask, b_factor in zip( + atom_types, atom_positions[i], atom_mask[i], b_factors[i] + ): + if mask < 0.5: + continue + + record_type = "ATOM" + name = atom_name if len(atom_name) == 4 else f" {atom_name}" + alt_loc = "" + insertion_code = "" + occupancy = 1.00 + element = atom_name[ + 0 + ] # Protein supports only C, N, O, S, this works. + charge = "" + + chain_tag = "A" + if(chain_index is not None): + chain_tag = chain_tags[chain_index[i]] + + # PDB is a columnar format, every space matters here! + atom_line = ( + f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" + f"{res_name_3:>3} {chain_tag:>1}" + f"{residue_index[i]:>4}{insertion_code:>1} " + f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" + f"{occupancy:>6.2f}{b_factor:>6.2f} " + f"{element:>2}{charge:>2}" + ) + pdb_lines.append(atom_line) + atom_index += 1 + + should_terminate = (i == n - 1) + if(chain_index is not None): + if(i != n - 1 and chain_index[i + 1] != prev_chain_index): + should_terminate = True + prev_chain_index = chain_index[i + 1] + + if(should_terminate): + # Close the chain. + chain_end = "TER" + chain_termination_line = ( + f"{chain_end:<6}{atom_index:>5} " + f"{res_1to3(aatype[i]):>3} " + f"{chain_tag:>1}{residue_index[i]:>4}" + ) + pdb_lines.append(chain_termination_line) + atom_index += 1 + + if(i != n - 1): + # "prev" is a misnomer here. This happens at the beginning of + # each new chain. + pdb_lines.extend(get_pdb_headers(prot, prev_chain_index)) + + pdb_lines.append("END") + pdb_lines.append("") + return "\n".join(pdb_lines) + + +def ideal_atom_mask(prot: Protein) -> np.ndarray: + """Computes an ideal atom mask. + + `Protein.atom_mask` typically is defined according to the atoms that are + reported in the PDB. This function computes a mask according to heavy atoms + that should be present in the given sequence of amino acids. + + Args: + prot: `Protein` whose fields are `numpy.ndarray` objects. + + Returns: + An ideal atom mask. + """ + return residue_constants.STANDARD_ATOM_MASK[prot.aatype] + + +def from_prediction( + features: FeatureDict, + result: ModelOutput, + b_factors: Optional[np.ndarray] = None, + chain_index: Optional[np.ndarray] = None, + remark: Optional[str] = None, + parents: Optional[Sequence[str]] = None, + parents_chain_index: Optional[Sequence[int]] = None +) -> Protein: + """Assembles a protein from a prediction. + + Args: + features: Dictionary holding model inputs. + result: Dictionary holding model outputs. + b_factors: (Optional) B-factors to use for the protein. + chain_index: (Optional) Chain indices for multi-chain predictions + remark: (Optional) Remark about the prediction + parents: (Optional) List of template names + Returns: + A protein instance. + """ + if b_factors is None: + b_factors = np.zeros_like(result["final_atom_mask"]) + + return Protein( + aatype=features["aatype"], + atom_positions=result["final_atom_positions"], + atom_mask=result["final_atom_mask"], + residue_index=features["residue_index"] + 1, + b_factors=b_factors, + chain_index=chain_index, + remark=remark, + parents=parents, + parents_chain_index=parents_chain_index, + ) diff --git a/gafl/openfold/np/relax/__init__.py b/gafl/openfold/np/relax/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25d1a5ba4be7300076d6f44af1541a33ca9e4ab1 --- /dev/null +++ b/gafl/openfold/np/relax/__init__.py @@ -0,0 +1,16 @@ +import os +import glob +import importlib as importlib + +_files = glob.glob(os.path.join(os.path.dirname(__file__), "*.py")) +__all__ = [ + os.path.basename(f)[:-3] + for f in _files + if os.path.isfile(f) and not f.endswith("__init__.py") +] +_modules = [(m, importlib.import_module("." + m, __name__)) for m in __all__] +for _m in _modules: + globals()[_m[0]] = _m[1] + +# Avoid needlessly cluttering the global namespace +del _files, _m, _modules diff --git a/gafl/openfold/np/relax/amber_minimize.py b/gafl/openfold/np/relax/amber_minimize.py new file mode 100644 index 0000000000000000000000000000000000000000..8f35a2d9fdf56fca3e89d822b7c6a8f56a265ccd --- /dev/null +++ b/gafl/openfold/np/relax/amber_minimize.py @@ -0,0 +1,612 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Restrained Amber Minimization of a structure.""" + +import io +import time +from typing import Collection, Optional, Sequence + +from absl import logging +from openfold.np import ( + protein, + residue_constants, +) +import openfold.utils.loss as loss +from openfold.np.relax import cleanup, utils +import ml_collections +import numpy as np +import openmm +from openmm import unit +from openmm import app as openmm_app +from openmm.app.internal.pdbstructure import PdbStructure + +ENERGY = unit.kilocalories_per_mole +LENGTH = unit.angstroms + + +def will_restrain(atom: openmm_app.Atom, rset: str) -> bool: + """Returns True if the atom will be restrained by the given restraint set.""" + + if rset == "non_hydrogen": + return atom.element.name != "hydrogen" + elif rset == "c_alpha": + return atom.name == "CA" + + +def _add_restraints( + system: openmm.System, + reference_pdb: openmm_app.PDBFile, + stiffness: unit.Unit, + rset: str, + exclude_residues: Sequence[int], +): + """Adds a harmonic potential that restrains the system to a structure.""" + assert rset in ["non_hydrogen", "c_alpha"] + + force = openmm.CustomExternalForce( + "0.5 * k * ((x-x0)^2 + (y-y0)^2 + (z-z0)^2)" + ) + force.addGlobalParameter("k", stiffness) + for p in ["x0", "y0", "z0"]: + force.addPerParticleParameter(p) + + for i, atom in enumerate(reference_pdb.topology.atoms()): + if atom.residue.index in exclude_residues: + continue + if will_restrain(atom, rset): + force.addParticle(i, reference_pdb.positions[i]) + logging.info( + "Restraining %d / %d particles.", + force.getNumParticles(), + system.getNumParticles(), + ) + system.addForce(force) + + +def _openmm_minimize( + pdb_str: str, + max_iterations: int, + tolerance: unit.Unit, + stiffness: unit.Unit, + restraint_set: str, + exclude_residues: Sequence[int], + use_gpu: bool, +): + """Minimize energy via openmm.""" + + pdb_file = io.StringIO(pdb_str) + pdb = openmm_app.PDBFile(pdb_file) + + force_field = openmm_app.ForceField("amber99sb.xml") + constraints = openmm_app.HBonds + system = force_field.createSystem(pdb.topology, constraints=constraints) + if stiffness > 0 * ENERGY / (LENGTH ** 2): + _add_restraints(system, pdb, stiffness, restraint_set, exclude_residues) + + integrator = openmm.LangevinIntegrator(0, 0.01, 0.0) + platform = openmm.Platform.getPlatformByName("CUDA" if use_gpu else "CPU") + simulation = openmm_app.Simulation( + pdb.topology, system, integrator, platform + ) + simulation.context.setPositions(pdb.positions) + + ret = {} + state = simulation.context.getState(getEnergy=True, getPositions=True) + ret["einit"] = state.getPotentialEnergy().value_in_unit(ENERGY) + ret["posinit"] = state.getPositions(asNumpy=True).value_in_unit(LENGTH) + simulation.minimizeEnergy(maxIterations=max_iterations, tolerance=tolerance) + state = simulation.context.getState(getEnergy=True, getPositions=True) + ret["efinal"] = state.getPotentialEnergy().value_in_unit(ENERGY) + ret["pos"] = state.getPositions(asNumpy=True).value_in_unit(LENGTH) + ret["min_pdb"] = _get_pdb_string(simulation.topology, state.getPositions()) + return ret + + +def _get_pdb_string(topology: openmm_app.Topology, positions: unit.Quantity): + """Returns a pdb string provided OpenMM topology and positions.""" + with io.StringIO() as f: + openmm_app.PDBFile.writeFile(topology, positions, f) + return f.getvalue() + + +def _check_cleaned_atoms(pdb_cleaned_string: str, pdb_ref_string: str): + """Checks that no atom positions have been altered by cleaning.""" + cleaned = openmm_app.PDBFile(io.StringIO(pdb_cleaned_string)) + reference = openmm_app.PDBFile(io.StringIO(pdb_ref_string)) + + cl_xyz = np.array(cleaned.getPositions().value_in_unit(LENGTH)) + ref_xyz = np.array(reference.getPositions().value_in_unit(LENGTH)) + + for ref_res, cl_res in zip( + reference.topology.residues(), cleaned.topology.residues() + ): + assert ref_res.name == cl_res.name + for rat in ref_res.atoms(): + for cat in cl_res.atoms(): + if cat.name == rat.name: + if not np.array_equal( + cl_xyz[cat.index], ref_xyz[rat.index] + ): + raise ValueError( + f"Coordinates of cleaned atom {cat} do not match " + f"coordinates of reference atom {rat}." + ) + + +def _check_residues_are_well_defined(prot: protein.Protein): + """Checks that all residues contain non-empty atom sets.""" + if (prot.atom_mask.sum(axis=-1) == 0).any(): + raise ValueError( + "Amber minimization can only be performed on proteins with" + " well-defined residues. This protein contains at least" + " one residue with no atoms." + ) + + +def _check_atom_mask_is_ideal(prot): + """Sanity-check the atom mask is ideal, up to a possible OXT.""" + atom_mask = prot.atom_mask + ideal_atom_mask = protein.ideal_atom_mask(prot) + utils.assert_equal_nonterminal_atom_types(atom_mask, ideal_atom_mask) + + +def clean_protein(prot: protein.Protein, checks: bool = True): + """Adds missing atoms to Protein instance. + + Args: + prot: A `protein.Protein` instance. + checks: A `bool` specifying whether to add additional checks to the cleaning + process. + + Returns: + pdb_string: A string of the cleaned protein. + """ + _check_atom_mask_is_ideal(prot) + + # Clean pdb. + prot_pdb_string = protein.to_pdb(prot) + pdb_file = io.StringIO(prot_pdb_string) + alterations_info = {} + fixed_pdb = cleanup.fix_pdb(pdb_file, alterations_info) + fixed_pdb_file = io.StringIO(fixed_pdb) + pdb_structure = PdbStructure(fixed_pdb_file) + cleanup.clean_structure(pdb_structure, alterations_info) + + logging.info("alterations info: %s", alterations_info) + + # Write pdb file of cleaned structure. + as_file = openmm_app.PDBFile(pdb_structure) + pdb_string = _get_pdb_string(as_file.getTopology(), as_file.getPositions()) + if checks: + _check_cleaned_atoms(pdb_string, prot_pdb_string) + return pdb_string + + +def make_atom14_positions(prot): + """Constructs denser atom positions (14 dimensions instead of 37).""" + restype_atom14_to_atom37 = [] # mapping (restype, atom14) --> atom37 + restype_atom37_to_atom14 = [] # mapping (restype, atom37) --> atom14 + restype_atom14_mask = [] + + for rt in residue_constants.restypes: + atom_names = residue_constants.restype_name_to_atom14_names[ + residue_constants.restype_1to3[rt] + ] + + restype_atom14_to_atom37.append( + [ + (residue_constants.atom_order[name] if name else 0) + for name in atom_names + ] + ) + + atom_name_to_idx14 = {name: i for i, name in enumerate(atom_names)} + restype_atom37_to_atom14.append( + [ + (atom_name_to_idx14[name] if name in atom_name_to_idx14 else 0) + for name in residue_constants.atom_types + ] + ) + + restype_atom14_mask.append( + [(1.0 if name else 0.0) for name in atom_names] + ) + + # Add dummy mapping for restype 'UNK'. + restype_atom14_to_atom37.append([0] * 14) + restype_atom37_to_atom14.append([0] * 37) + restype_atom14_mask.append([0.0] * 14) + + restype_atom14_to_atom37 = np.array( + restype_atom14_to_atom37, dtype=int + ) + restype_atom37_to_atom14 = np.array( + restype_atom37_to_atom14, dtype=int + ) + restype_atom14_mask = np.array(restype_atom14_mask, dtype=np.float32) + + # Create the mapping for (residx, atom14) --> atom37, i.e. an array + # with shape (num_res, 14) containing the atom37 indices for this protein. + residx_atom14_to_atom37 = restype_atom14_to_atom37[prot["aatype"]] + residx_atom14_mask = restype_atom14_mask[prot["aatype"]] + + # Create a mask for known ground truth positions. + residx_atom14_gt_mask = residx_atom14_mask * np.take_along_axis( + prot["all_atom_mask"], residx_atom14_to_atom37, axis=1 + ).astype(np.float32) + + # Gather the ground truth positions. + residx_atom14_gt_positions = residx_atom14_gt_mask[:, :, None] * ( + np.take_along_axis( + prot["all_atom_positions"], + residx_atom14_to_atom37[..., None], + axis=1, + ) + ) + + prot["atom14_atom_exists"] = residx_atom14_mask + prot["atom14_gt_exists"] = residx_atom14_gt_mask + prot["atom14_gt_positions"] = residx_atom14_gt_positions + + prot["residx_atom14_to_atom37"] = residx_atom14_to_atom37.astype(np.int64) + + # Create the gather indices for mapping back. + residx_atom37_to_atom14 = restype_atom37_to_atom14[prot["aatype"]] + prot["residx_atom37_to_atom14"] = residx_atom37_to_atom14.astype(np.int64) + + # Create the corresponding mask. + restype_atom37_mask = np.zeros([21, 37], dtype=np.float32) + for restype, restype_letter in enumerate(residue_constants.restypes): + restype_name = residue_constants.restype_1to3[restype_letter] + atom_names = residue_constants.residue_atoms[restype_name] + for atom_name in atom_names: + atom_type = residue_constants.atom_order[atom_name] + restype_atom37_mask[restype, atom_type] = 1 + + residx_atom37_mask = restype_atom37_mask[prot["aatype"]] + prot["atom37_atom_exists"] = residx_atom37_mask + + # As the atom naming is ambiguous for 7 of the 20 amino acids, provide + # alternative ground truth coordinates where the naming is swapped + restype_3 = [ + residue_constants.restype_1to3[res] + for res in residue_constants.restypes + ] + restype_3 += ["UNK"] + + # Matrices for renaming ambiguous atoms. + all_matrices = {res: np.eye(14, dtype=np.float32) for res in restype_3} + for resname, swap in residue_constants.residue_atom_renaming_swaps.items(): + correspondences = np.arange(14) + for source_atom_swap, target_atom_swap in swap.items(): + source_index = residue_constants.restype_name_to_atom14_names[ + resname + ].index(source_atom_swap) + target_index = residue_constants.restype_name_to_atom14_names[ + resname + ].index(target_atom_swap) + correspondences[source_index] = target_index + correspondences[target_index] = source_index + renaming_matrix = np.zeros((14, 14), dtype=np.float32) + for index, correspondence in enumerate(correspondences): + renaming_matrix[index, correspondence] = 1.0 + all_matrices[resname] = renaming_matrix.astype(np.float32) + renaming_matrices = np.stack( + [all_matrices[restype] for restype in restype_3] + ) + + # Pick the transformation matrices for the given residue sequence + # shape (num_res, 14, 14). + renaming_transform = renaming_matrices[prot["aatype"]] + + # Apply it to the ground truth positions. shape (num_res, 14, 3). + alternative_gt_positions = np.einsum( + "rac,rab->rbc", residx_atom14_gt_positions, renaming_transform + ) + prot["atom14_alt_gt_positions"] = alternative_gt_positions + + # Create the mask for the alternative ground truth (differs from the + # ground truth mask, if only one of the atoms in an ambiguous pair has a + # ground truth position). + alternative_gt_mask = np.einsum( + "ra,rab->rb", residx_atom14_gt_mask, renaming_transform + ) + + prot["atom14_alt_gt_exists"] = alternative_gt_mask + + # Create an ambiguous atoms mask. shape: (21, 14). + restype_atom14_is_ambiguous = np.zeros((21, 14), dtype=np.float32) + for resname, swap in residue_constants.residue_atom_renaming_swaps.items(): + for atom_name1, atom_name2 in swap.items(): + restype = residue_constants.restype_order[ + residue_constants.restype_3to1[resname] + ] + atom_idx1 = residue_constants.restype_name_to_atom14_names[ + resname + ].index(atom_name1) + atom_idx2 = residue_constants.restype_name_to_atom14_names[ + resname + ].index(atom_name2) + restype_atom14_is_ambiguous[restype, atom_idx1] = 1 + restype_atom14_is_ambiguous[restype, atom_idx2] = 1 + + # From this create an ambiguous_mask for the given sequence. + prot["atom14_atom_is_ambiguous"] = restype_atom14_is_ambiguous[ + prot["aatype"] + ] + + return prot + + +def find_violations(prot_np: protein.Protein): + """Analyzes a protein and returns structural violation information. + + Args: + prot_np: A protein. + + Returns: + violations: A `dict` of structure components with structural violations. + violation_metrics: A `dict` of violation metrics. + """ + batch = { + "aatype": prot_np.aatype, + "all_atom_positions": prot_np.atom_positions.astype(np.float32), + "all_atom_mask": prot_np.atom_mask.astype(np.float32), + "residue_index": prot_np.residue_index, + } + + batch["seq_mask"] = np.ones_like(batch["aatype"], np.float32) + batch = make_atom14_positions(batch) + + violations = loss.find_structural_violations_np( + batch=batch, + atom14_pred_positions=batch["atom14_gt_positions"], + config=ml_collections.ConfigDict( + { + "violation_tolerance_factor": 12, # Taken from model config. + "clash_overlap_tolerance": 1.5, # Taken from model config. + } + ), + ) + violation_metrics = loss.compute_violation_metrics_np( + batch=batch, + atom14_pred_positions=batch["atom14_gt_positions"], + violations=violations, + ) + + return violations, violation_metrics + + +def get_violation_metrics(prot: protein.Protein): + """Computes violation and alignment metrics.""" + structural_violations, struct_metrics = find_violations(prot) + violation_idx = np.flatnonzero( + structural_violations["total_per_residue_violations_mask"] + ) + + struct_metrics["residue_violations"] = violation_idx + struct_metrics["num_residue_violations"] = len(violation_idx) + struct_metrics["structural_violations"] = structural_violations + return struct_metrics + + +def _run_one_iteration( + *, + pdb_string: str, + max_iterations: int, + tolerance: float, + stiffness: float, + restraint_set: str, + max_attempts: int, + exclude_residues: Optional[Collection[int]] = None, + use_gpu: bool, +): + """Runs the minimization pipeline. + + Args: + pdb_string: A pdb string. + max_iterations: An `int` specifying the maximum number of L-BFGS iterations. + A value of 0 specifies no limit. + tolerance: kcal/mol, the energy tolerance of L-BFGS. + stiffness: kcal/mol A**2, spring constant of heavy atom restraining + potential. + restraint_set: The set of atoms to restrain. + max_attempts: The maximum number of minimization attempts. + exclude_residues: An optional list of zero-indexed residues to exclude from + restraints. + use_gpu: Whether to run relaxation on GPU + Returns: + A `dict` of minimization info. + """ + exclude_residues = exclude_residues or [] + + # Assign physical dimensions. + tolerance = tolerance * ENERGY + stiffness = stiffness * ENERGY / (LENGTH ** 2) + + start = time.perf_counter() + minimized = False + attempts = 0 + while not minimized and attempts < max_attempts: + attempts += 1 + try: + logging.info( + "Minimizing protein, attempt %d of %d.", attempts, max_attempts + ) + ret = _openmm_minimize( + pdb_string, + max_iterations=max_iterations, + tolerance=tolerance, + stiffness=stiffness, + restraint_set=restraint_set, + exclude_residues=exclude_residues, + use_gpu=use_gpu, + ) + minimized = True + except Exception as e: # pylint: disable=broad-except + print(e) + logging.info(e) + if not minimized: + raise ValueError(f"Minimization failed after {max_attempts} attempts.") + ret["opt_time"] = time.perf_counter() - start + ret["min_attempts"] = attempts + return ret + + +def run_pipeline( + prot: protein.Protein, + stiffness: float, + use_gpu: bool, + max_outer_iterations: int = 1, + place_hydrogens_every_iteration: bool = True, + max_iterations: int = 0, + tolerance: float = 2.39, + restraint_set: str = "non_hydrogen", + max_attempts: int = 100, + checks: bool = True, + exclude_residues: Optional[Sequence[int]] = None, +): + """Run iterative amber relax. + + Successive relax iterations are performed until all violations have been + resolved. Each iteration involves a restrained Amber minimization, with + restraint exclusions determined by violation-participating residues. + + Args: + prot: A protein to be relaxed. + stiffness: kcal/mol A**2, the restraint stiffness. + use_gpu: Whether to run on GPU + max_outer_iterations: The maximum number of iterative minimization. + place_hydrogens_every_iteration: Whether hydrogens are re-initialized + prior to every minimization. + max_iterations: An `int` specifying the maximum number of L-BFGS steps + per relax iteration. A value of 0 specifies no limit. + tolerance: kcal/mol, the energy tolerance of L-BFGS. + The default value is the OpenMM default. + restraint_set: The set of atoms to restrain. + max_attempts: The maximum number of minimization attempts per iteration. + checks: Whether to perform cleaning checks. + exclude_residues: An optional list of zero-indexed residues to exclude from + restraints. + + Returns: + out: A dictionary of output values. + """ + + # `protein.to_pdb` will strip any poorly-defined residues so we need to + # perform this check before `clean_protein`. + _check_residues_are_well_defined(prot) + pdb_string = clean_protein(prot, checks=checks) + + exclude_residues = exclude_residues or [] + exclude_residues = set(exclude_residues) + violations = np.inf + iteration = 0 + + while violations > 0 and iteration < max_outer_iterations: + ret = _run_one_iteration( + pdb_string=pdb_string, + exclude_residues=exclude_residues, + max_iterations=max_iterations, + tolerance=tolerance, + stiffness=stiffness, + restraint_set=restraint_set, + max_attempts=max_attempts, + use_gpu=use_gpu, + ) + prot = protein.from_pdb_string(ret["min_pdb"]) + if place_hydrogens_every_iteration: + pdb_string = clean_protein(prot, checks=True) + else: + pdb_string = ret["min_pdb"] + ret.update(get_violation_metrics(prot)) + ret.update( + { + "num_exclusions": len(exclude_residues), + "iteration": iteration, + } + ) + violations = ret["violations_per_residue"] + exclude_residues = exclude_residues.union(ret["residue_violations"]) + + logging.info( + "Iteration completed: Einit %.2f Efinal %.2f Time %.2f s " + "num residue violations %d num residue exclusions %d ", + ret["einit"], + ret["efinal"], + ret["opt_time"], + ret["num_residue_violations"], + ret["num_exclusions"], + ) + iteration += 1 + return ret + + +def get_initial_energies( + pdb_strs: Sequence[str], + stiffness: float = 0.0, + restraint_set: str = "non_hydrogen", + exclude_residues: Optional[Sequence[int]] = None, +): + """Returns initial potential energies for a sequence of PDBs. + + Assumes the input PDBs are ready for minimization, and all have the same + topology. + Allows time to be saved by not pdbfixing / rebuilding the system. + + Args: + pdb_strs: List of PDB strings. + stiffness: kcal/mol A**2, spring constant of heavy atom restraining + potential. + restraint_set: Which atom types to restrain. + exclude_residues: An optional list of zero-indexed residues to exclude from + restraints. + + Returns: + A list of initial energies in the same order as pdb_strs. + """ + exclude_residues = exclude_residues or [] + + openmm_pdbs = [ + openmm_app.PDBFile(PdbStructure(io.StringIO(p))) for p in pdb_strs + ] + force_field = openmm_app.ForceField("amber99sb.xml") + system = force_field.createSystem( + openmm_pdbs[0].topology, constraints=openmm_app.HBonds + ) + stiffness = stiffness * ENERGY / (LENGTH ** 2) + if stiffness > 0 * ENERGY / (LENGTH ** 2): + _add_restraints( + system, openmm_pdbs[0], stiffness, restraint_set, exclude_residues + ) + simulation = openmm_app.Simulation( + openmm_pdbs[0].topology, + system, + openmm.LangevinIntegrator(0, 0.01, 0.0), + openmm.Platform.getPlatformByName("CPU"), + ) + energies = [] + for pdb in openmm_pdbs: + try: + simulation.context.setPositions(pdb.positions) + state = simulation.context.getState(getEnergy=True) + energies.append(state.getPotentialEnergy().value_in_unit(ENERGY)) + except Exception as e: # pylint: disable=broad-except + logging.error( + "Error getting initial energy, returning large value %s", e + ) + energies.append(unit.Quantity(1e20, ENERGY)) + return energies diff --git a/gafl/openfold/np/relax/cleanup.py b/gafl/openfold/np/relax/cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f59a48b3b2184c68ccbbce9048b6a137086ca4 --- /dev/null +++ b/gafl/openfold/np/relax/cleanup.py @@ -0,0 +1,131 @@ +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cleans up a PDB file using pdbfixer in preparation for OpenMM simulations. + +fix_pdb uses a third-party tool. We also support fixing some additional edge +cases like removing chains of length one (see clean_structure). +""" +import io + +import pdbfixer +from simtk.openmm import app +from simtk.openmm.app import element + + +def fix_pdb(pdbfile, alterations_info): + """Apply pdbfixer to the contents of a PDB file; return a PDB string result. + + 1) Replaces nonstandard residues. + 2) Removes heterogens (non protein residues) including water. + 3) Adds missing residues and missing atoms within existing residues. + 4) Adds hydrogens assuming pH=7.0. + 5) KeepIds is currently true, so the fixer must keep the existing chain and + residue identifiers. This will fail for some files in wider PDB that have + invalid IDs. + + Args: + pdbfile: Input PDB file handle. + alterations_info: A dict that will store details of changes made. + + Returns: + A PDB string representing the fixed structure. + """ + fixer = pdbfixer.PDBFixer(pdbfile=pdbfile) + fixer.findNonstandardResidues() + alterations_info["nonstandard_residues"] = fixer.nonstandardResidues + fixer.replaceNonstandardResidues() + _remove_heterogens(fixer, alterations_info, keep_water=False) + fixer.findMissingResidues() + alterations_info["missing_residues"] = fixer.missingResidues + fixer.findMissingAtoms() + alterations_info["missing_heavy_atoms"] = fixer.missingAtoms + alterations_info["missing_terminals"] = fixer.missingTerminals + fixer.addMissingAtoms(seed=0) + fixer.addMissingHydrogens() + out_handle = io.StringIO() + app.PDBFile.writeFile( + fixer.topology, fixer.positions, out_handle, keepIds=True + ) + return out_handle.getvalue() + + +def clean_structure(pdb_structure, alterations_info): + """Applies additional fixes to an OpenMM structure, to handle edge cases. + + Args: + pdb_structure: An OpenMM structure to modify and fix. + alterations_info: A dict that will store details of changes made. + """ + _replace_met_se(pdb_structure, alterations_info) + _remove_chains_of_length_one(pdb_structure, alterations_info) + + +def _remove_heterogens(fixer, alterations_info, keep_water): + """Removes the residues that Pdbfixer considers to be heterogens. + + Args: + fixer: A Pdbfixer instance. + alterations_info: A dict that will store details of changes made. + keep_water: If True, water (HOH) is not considered to be a heterogen. + """ + initial_resnames = set() + for chain in fixer.topology.chains(): + for residue in chain.residues(): + initial_resnames.add(residue.name) + fixer.removeHeterogens(keepWater=keep_water) + final_resnames = set() + for chain in fixer.topology.chains(): + for residue in chain.residues(): + final_resnames.add(residue.name) + alterations_info["removed_heterogens"] = initial_resnames.difference( + final_resnames + ) + + +def _replace_met_se(pdb_structure, alterations_info): + """Replace the Se in any MET residues that were not marked as modified.""" + modified_met_residues = [] + for res in pdb_structure.iter_residues(): + name = res.get_name_with_spaces().strip() + if name == "MET": + s_atom = res.get_atom("SD") + if s_atom.element_symbol == "Se": + s_atom.element_symbol = "S" + s_atom.element = element.get_by_symbol("S") + modified_met_residues.append(s_atom.residue_number) + alterations_info["Se_in_MET"] = modified_met_residues + + +def _remove_chains_of_length_one(pdb_structure, alterations_info): + """Removes chains that correspond to a single amino acid. + + A single amino acid in a chain is both N and C terminus. There is no force + template for this case. + + Args: + pdb_structure: An OpenMM pdb_structure to modify and fix. + alterations_info: A dict that will store details of changes made. + """ + removed_chains = {} + for model in pdb_structure.iter_models(): + valid_chains = [c for c in model.iter_chains() if len(c) > 1] + invalid_chain_ids = [ + c.chain_id for c in model.iter_chains() if len(c) <= 1 + ] + model.chains = valid_chains + for chain_id in invalid_chain_ids: + model.chains_by_id.pop(chain_id) + removed_chains[model.number] = invalid_chain_ids + alterations_info["removed_chains"] = removed_chains diff --git a/gafl/openfold/np/relax/relax.py b/gafl/openfold/np/relax/relax.py new file mode 100644 index 0000000000000000000000000000000000000000..8feee742d033ee3165f5975cb14e13c599bfb364 --- /dev/null +++ b/gafl/openfold/np/relax/relax.py @@ -0,0 +1,90 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Amber relaxation.""" +from typing import Any, Dict, Sequence, Tuple +from openfold.np import protein +from openfold.np.relax import amber_minimize, utils +import numpy as np + + +class AmberRelaxation(object): + """Amber relaxation.""" + def __init__( + self, + *, + max_iterations: int, + tolerance: float, + stiffness: float, + exclude_residues: Sequence[int], + max_outer_iterations: int, + use_gpu: bool, + ): + """Initialize Amber Relaxer. + + Args: + max_iterations: Maximum number of L-BFGS iterations. 0 means no max. + tolerance: kcal/mol, the energy tolerance of L-BFGS. + stiffness: kcal/mol A**2, spring constant of heavy atom restraining + potential. + exclude_residues: Residues to exclude from per-atom restraining. + Zero-indexed. + max_outer_iterations: Maximum number of violation-informed relax + iterations. A value of 1 will run the non-iterative procedure used in + CASP14. Use 20 so that >95% of the bad cases are relaxed. Relax finishes + as soon as there are no violations, hence in most cases this causes no + slowdown. In the worst case we do 20 outer iterations. + use_gpu: Whether to run on GPU + """ + + self._max_iterations = max_iterations + self._tolerance = tolerance + self._stiffness = stiffness + self._exclude_residues = exclude_residues + self._max_outer_iterations = max_outer_iterations + self._use_gpu = use_gpu + + def process( + self, *, prot: protein.Protein + ) -> Tuple[str, Dict[str, Any], np.ndarray]: + """Runs Amber relax on a prediction, adds hydrogens, returns PDB string.""" + out = amber_minimize.run_pipeline( + prot=prot, + max_iterations=self._max_iterations, + tolerance=self._tolerance, + stiffness=self._stiffness, + exclude_residues=self._exclude_residues, + max_outer_iterations=self._max_outer_iterations, + use_gpu=self._use_gpu, + ) + min_pos = out["pos"] + start_pos = out["posinit"] + rmsd = np.sqrt(np.sum((start_pos - min_pos) ** 2) / start_pos.shape[0]) + debug_data = { + "initial_energy": out["einit"], + "final_energy": out["efinal"], + "attempts": out["min_attempts"], + "rmsd": rmsd, + } + pdb_str = amber_minimize.clean_protein(prot) + min_pdb = utils.overwrite_pdb_coordinates(pdb_str, min_pos) + min_pdb = utils.overwrite_b_factors(min_pdb, prot.b_factors) + utils.assert_equal_nonterminal_atom_types( + protein.from_pdb_string(min_pdb).atom_mask, prot.atom_mask + ) + violations = out["structural_violations"][ + "total_per_residue_violations_mask" + ] + return min_pdb, debug_data, violations diff --git a/gafl/openfold/np/relax/utils.py b/gafl/openfold/np/relax/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e41aea524a97ddd563dc32963b4671f438c7ae4 --- /dev/null +++ b/gafl/openfold/np/relax/utils.py @@ -0,0 +1,88 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utils for minimization.""" +import io +from openfold.np import residue_constants +from Bio import PDB +import numpy as np +# simtk.openmm is not supported anymore. Remove simtk. +# https://github.com/openmm/openmm/releases +from openmm import app as openmm_app +from openmm.app.internal.pdbstructure import PdbStructure + + +def overwrite_pdb_coordinates(pdb_str: str, pos) -> str: + pdb_file = io.StringIO(pdb_str) + structure = PdbStructure(pdb_file) + topology = openmm_app.PDBFile(structure).getTopology() + with io.StringIO() as f: + openmm_app.PDBFile.writeFile(topology, pos, f) + return f.getvalue() + + +def overwrite_b_factors(pdb_str: str, bfactors: np.ndarray) -> str: + """Overwrites the B-factors in pdb_str with contents of bfactors array. + + Args: + pdb_str: An input PDB string. + bfactors: A numpy array with shape [1, n_residues, 37]. We assume that the + B-factors are per residue; i.e. that the nonzero entries are identical in + [0, i, :]. + + Returns: + A new PDB string with the B-factors replaced. + """ + if bfactors.shape[-1] != residue_constants.atom_type_num: + raise ValueError( + f"Invalid final dimension size for bfactors: {bfactors.shape[-1]}." + ) + + parser = PDB.PDBParser(QUIET=True) + handle = io.StringIO(pdb_str) + structure = parser.get_structure("", handle) + + curr_resid = ("", "", "") + idx = -1 + for atom in structure.get_atoms(): + atom_resid = atom.parent.get_id() + if atom_resid != curr_resid: + idx += 1 + if idx >= bfactors.shape[0]: + raise ValueError( + "Index into bfactors exceeds number of residues. " + "B-factors shape: {shape}, idx: {idx}." + ) + curr_resid = atom_resid + atom.bfactor = bfactors[idx, residue_constants.atom_order["CA"]] + + new_pdb = io.StringIO() + pdb_io = PDB.PDBIO() + pdb_io.set_structure(structure) + pdb_io.save(new_pdb) + return new_pdb.getvalue() + + +def assert_equal_nonterminal_atom_types( + atom_mask: np.ndarray, ref_atom_mask: np.ndarray +): + """Checks that pre- and post-minimized proteins have same atom set.""" + # Ignore any terminal OXT atoms which may have been added by minimization. + oxt = residue_constants.atom_order["OXT"] + no_oxt_mask = np.ones(shape=atom_mask.shape, dtype=np.bool) + no_oxt_mask[..., oxt] = False + np.testing.assert_almost_equal( + ref_atom_mask[no_oxt_mask], atom_mask[no_oxt_mask] + ) diff --git a/gafl/openfold/np/residue_constants.py b/gafl/openfold/np/residue_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3eae6fe48634e2dee88375c4a38c293305c5b0 --- /dev/null +++ b/gafl/openfold/np/residue_constants.py @@ -0,0 +1,1310 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Constants used in AlphaFold.""" + +import collections +import functools +from typing import Mapping, List, Tuple +from importlib import resources + +import numpy as np +import tree + +# Internal import (35fd). + + +# Distance from one CA to next CA [trans configuration: omega = 180]. +ca_ca = 3.80209737096 + +# Format: The list for each AA type contains chi1, chi2, chi3, chi4 in +# this order (or a relevant subset from chi1 onwards). ALA and GLY don't have +# chi angles so their chi angle lists are empty. +chi_angles_atoms = { + "ALA": [], + # Chi5 in arginine is always 0 +- 5 degrees, so ignore it. + "ARG": [ + ["N", "CA", "CB", "CG"], + ["CA", "CB", "CG", "CD"], + ["CB", "CG", "CD", "NE"], + ["CG", "CD", "NE", "CZ"], + ], + "ASN": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "OD1"]], + "ASP": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "OD1"]], + "CYS": [["N", "CA", "CB", "SG"]], + "GLN": [ + ["N", "CA", "CB", "CG"], + ["CA", "CB", "CG", "CD"], + ["CB", "CG", "CD", "OE1"], + ], + "GLU": [ + ["N", "CA", "CB", "CG"], + ["CA", "CB", "CG", "CD"], + ["CB", "CG", "CD", "OE1"], + ], + "GLY": [], + "HIS": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "ND1"]], + "ILE": [["N", "CA", "CB", "CG1"], ["CA", "CB", "CG1", "CD1"]], + "LEU": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]], + "LYS": [ + ["N", "CA", "CB", "CG"], + ["CA", "CB", "CG", "CD"], + ["CB", "CG", "CD", "CE"], + ["CG", "CD", "CE", "NZ"], + ], + "MET": [ + ["N", "CA", "CB", "CG"], + ["CA", "CB", "CG", "SD"], + ["CB", "CG", "SD", "CE"], + ], + "PHE": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]], + "PRO": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"]], + "SER": [["N", "CA", "CB", "OG"]], + "THR": [["N", "CA", "CB", "OG1"]], + "TRP": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]], + "TYR": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]], + "VAL": [["N", "CA", "CB", "CG1"]], +} + +# If chi angles given in fixed-length array, this matrix determines how to mask +# them for each AA type. The order is as per restype_order (see below). +chi_angles_mask = [ + [0.0, 0.0, 0.0, 0.0], # ALA + [1.0, 1.0, 1.0, 1.0], # ARG + [1.0, 1.0, 0.0, 0.0], # ASN + [1.0, 1.0, 0.0, 0.0], # ASP + [1.0, 0.0, 0.0, 0.0], # CYS + [1.0, 1.0, 1.0, 0.0], # GLN + [1.0, 1.0, 1.0, 0.0], # GLU + [0.0, 0.0, 0.0, 0.0], # GLY + [1.0, 1.0, 0.0, 0.0], # HIS + [1.0, 1.0, 0.0, 0.0], # ILE + [1.0, 1.0, 0.0, 0.0], # LEU + [1.0, 1.0, 1.0, 1.0], # LYS + [1.0, 1.0, 1.0, 0.0], # MET + [1.0, 1.0, 0.0, 0.0], # PHE + [1.0, 1.0, 0.0, 0.0], # PRO + [1.0, 0.0, 0.0, 0.0], # SER + [1.0, 0.0, 0.0, 0.0], # THR + [1.0, 1.0, 0.0, 0.0], # TRP + [1.0, 1.0, 0.0, 0.0], # TYR + [1.0, 0.0, 0.0, 0.0], # VAL +] + +# The following chi angles are pi periodic: they can be rotated by a multiple +# of pi without affecting the structure. +chi_pi_periodic = [ + [0.0, 0.0, 0.0, 0.0], # ALA + [0.0, 0.0, 0.0, 0.0], # ARG + [0.0, 0.0, 0.0, 0.0], # ASN + [0.0, 1.0, 0.0, 0.0], # ASP + [0.0, 0.0, 0.0, 0.0], # CYS + [0.0, 0.0, 0.0, 0.0], # GLN + [0.0, 0.0, 1.0, 0.0], # GLU + [0.0, 0.0, 0.0, 0.0], # GLY + [0.0, 0.0, 0.0, 0.0], # HIS + [0.0, 0.0, 0.0, 0.0], # ILE + [0.0, 0.0, 0.0, 0.0], # LEU + [0.0, 0.0, 0.0, 0.0], # LYS + [0.0, 0.0, 0.0, 0.0], # MET + [0.0, 1.0, 0.0, 0.0], # PHE + [0.0, 0.0, 0.0, 0.0], # PRO + [0.0, 0.0, 0.0, 0.0], # SER + [0.0, 0.0, 0.0, 0.0], # THR + [0.0, 0.0, 0.0, 0.0], # TRP + [0.0, 1.0, 0.0, 0.0], # TYR + [0.0, 0.0, 0.0, 0.0], # VAL + [0.0, 0.0, 0.0, 0.0], # UNK +] + +# Atoms positions relative to the 8 rigid groups, defined by the pre-omega, phi, +# psi and chi angles: +# 0: 'backbone group', +# 1: 'pre-omega-group', (empty) +# 2: 'phi-group', (currently empty, because it defines only hydrogens) +# 3: 'psi-group', +# 4,5,6,7: 'chi1,2,3,4-group' +# The atom positions are relative to the axis-end-atom of the corresponding +# rotation axis. The x-axis is in direction of the rotation axis, and the y-axis +# is defined such that the dihedral-angle-definiting atom (the last entry in +# chi_angles_atoms above) is in the xy-plane (with a positive y-coordinate). +# format: [atomname, group_idx, rel_position] +rigid_group_atom_positions = { + "ALA": [ + ["N", 0, (-0.525, 1.363, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, -0.000, -0.000)], + ["CB", 0, (-0.529, -0.774, -1.205)], + ["O", 3, (0.627, 1.062, 0.000)], + ], + "ARG": [ + ["N", 0, (-0.524, 1.362, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, -0.000, -0.000)], + ["CB", 0, (-0.524, -0.778, -1.209)], + ["O", 3, (0.626, 1.062, 0.000)], + ["CG", 4, (0.616, 1.390, -0.000)], + ["CD", 5, (0.564, 1.414, 0.000)], + ["NE", 6, (0.539, 1.357, -0.000)], + ["NH1", 7, (0.206, 2.301, 0.000)], + ["NH2", 7, (2.078, 0.978, -0.000)], + ["CZ", 7, (0.758, 1.093, -0.000)], + ], + "ASN": [ + ["N", 0, (-0.536, 1.357, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, -0.000, -0.000)], + ["CB", 0, (-0.531, -0.787, -1.200)], + ["O", 3, (0.625, 1.062, 0.000)], + ["CG", 4, (0.584, 1.399, 0.000)], + ["ND2", 5, (0.593, -1.188, 0.001)], + ["OD1", 5, (0.633, 1.059, 0.000)], + ], + "ASP": [ + ["N", 0, (-0.525, 1.362, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.527, 0.000, -0.000)], + ["CB", 0, (-0.526, -0.778, -1.208)], + ["O", 3, (0.626, 1.062, -0.000)], + ["CG", 4, (0.593, 1.398, -0.000)], + ["OD1", 5, (0.610, 1.091, 0.000)], + ["OD2", 5, (0.592, -1.101, -0.003)], + ], + "CYS": [ + ["N", 0, (-0.522, 1.362, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.524, 0.000, 0.000)], + ["CB", 0, (-0.519, -0.773, -1.212)], + ["O", 3, (0.625, 1.062, -0.000)], + ["SG", 4, (0.728, 1.653, 0.000)], + ], + "GLN": [ + ["N", 0, (-0.526, 1.361, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, 0.000, 0.000)], + ["CB", 0, (-0.525, -0.779, -1.207)], + ["O", 3, (0.626, 1.062, -0.000)], + ["CG", 4, (0.615, 1.393, 0.000)], + ["CD", 5, (0.587, 1.399, -0.000)], + ["NE2", 6, (0.593, -1.189, -0.001)], + ["OE1", 6, (0.634, 1.060, 0.000)], + ], + "GLU": [ + ["N", 0, (-0.528, 1.361, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, -0.000, -0.000)], + ["CB", 0, (-0.526, -0.781, -1.207)], + ["O", 3, (0.626, 1.062, 0.000)], + ["CG", 4, (0.615, 1.392, 0.000)], + ["CD", 5, (0.600, 1.397, 0.000)], + ["OE1", 6, (0.607, 1.095, -0.000)], + ["OE2", 6, (0.589, -1.104, -0.001)], + ], + "GLY": [ + ["N", 0, (-0.572, 1.337, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.517, -0.000, -0.000)], + ["O", 3, (0.626, 1.062, -0.000)], + ], + "HIS": [ + ["N", 0, (-0.527, 1.360, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, 0.000, 0.000)], + ["CB", 0, (-0.525, -0.778, -1.208)], + ["O", 3, (0.625, 1.063, 0.000)], + ["CG", 4, (0.600, 1.370, -0.000)], + ["CD2", 5, (0.889, -1.021, 0.003)], + ["ND1", 5, (0.744, 1.160, -0.000)], + ["CE1", 5, (2.030, 0.851, 0.002)], + ["NE2", 5, (2.145, -0.466, 0.004)], + ], + "ILE": [ + ["N", 0, (-0.493, 1.373, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.527, -0.000, -0.000)], + ["CB", 0, (-0.536, -0.793, -1.213)], + ["O", 3, (0.627, 1.062, -0.000)], + ["CG1", 4, (0.534, 1.437, -0.000)], + ["CG2", 4, (0.540, -0.785, -1.199)], + ["CD1", 5, (0.619, 1.391, 0.000)], + ], + "LEU": [ + ["N", 0, (-0.520, 1.363, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, -0.000, -0.000)], + ["CB", 0, (-0.522, -0.773, -1.214)], + ["O", 3, (0.625, 1.063, -0.000)], + ["CG", 4, (0.678, 1.371, 0.000)], + ["CD1", 5, (0.530, 1.430, -0.000)], + ["CD2", 5, (0.535, -0.774, 1.200)], + ], + "LYS": [ + ["N", 0, (-0.526, 1.362, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, 0.000, 0.000)], + ["CB", 0, (-0.524, -0.778, -1.208)], + ["O", 3, (0.626, 1.062, -0.000)], + ["CG", 4, (0.619, 1.390, 0.000)], + ["CD", 5, (0.559, 1.417, 0.000)], + ["CE", 6, (0.560, 1.416, 0.000)], + ["NZ", 7, (0.554, 1.387, 0.000)], + ], + "MET": [ + ["N", 0, (-0.521, 1.364, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, 0.000, 0.000)], + ["CB", 0, (-0.523, -0.776, -1.210)], + ["O", 3, (0.625, 1.062, -0.000)], + ["CG", 4, (0.613, 1.391, -0.000)], + ["SD", 5, (0.703, 1.695, 0.000)], + ["CE", 6, (0.320, 1.786, -0.000)], + ], + "PHE": [ + ["N", 0, (-0.518, 1.363, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.524, 0.000, -0.000)], + ["CB", 0, (-0.525, -0.776, -1.212)], + ["O", 3, (0.626, 1.062, -0.000)], + ["CG", 4, (0.607, 1.377, 0.000)], + ["CD1", 5, (0.709, 1.195, -0.000)], + ["CD2", 5, (0.706, -1.196, 0.000)], + ["CE1", 5, (2.102, 1.198, -0.000)], + ["CE2", 5, (2.098, -1.201, -0.000)], + ["CZ", 5, (2.794, -0.003, -0.001)], + ], + "PRO": [ + ["N", 0, (-0.566, 1.351, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.527, -0.000, 0.000)], + ["CB", 0, (-0.546, -0.611, -1.293)], + ["O", 3, (0.621, 1.066, 0.000)], + ["CG", 4, (0.382, 1.445, 0.0)], + # ['CD', 5, (0.427, 1.440, 0.0)], + ["CD", 5, (0.477, 1.424, 0.0)], # manually made angle 2 degrees larger + ], + "SER": [ + ["N", 0, (-0.529, 1.360, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, -0.000, -0.000)], + ["CB", 0, (-0.518, -0.777, -1.211)], + ["O", 3, (0.626, 1.062, -0.000)], + ["OG", 4, (0.503, 1.325, 0.000)], + ], + "THR": [ + ["N", 0, (-0.517, 1.364, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.526, 0.000, -0.000)], + ["CB", 0, (-0.516, -0.793, -1.215)], + ["O", 3, (0.626, 1.062, 0.000)], + ["CG2", 4, (0.550, -0.718, -1.228)], + ["OG1", 4, (0.472, 1.353, 0.000)], + ], + "TRP": [ + ["N", 0, (-0.521, 1.363, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.525, -0.000, 0.000)], + ["CB", 0, (-0.523, -0.776, -1.212)], + ["O", 3, (0.627, 1.062, 0.000)], + ["CG", 4, (0.609, 1.370, -0.000)], + ["CD1", 5, (0.824, 1.091, 0.000)], + ["CD2", 5, (0.854, -1.148, -0.005)], + ["CE2", 5, (2.186, -0.678, -0.007)], + ["CE3", 5, (0.622, -2.530, -0.007)], + ["NE1", 5, (2.140, 0.690, -0.004)], + ["CH2", 5, (3.028, -2.890, -0.013)], + ["CZ2", 5, (3.283, -1.543, -0.011)], + ["CZ3", 5, (1.715, -3.389, -0.011)], + ], + "TYR": [ + ["N", 0, (-0.522, 1.362, 0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.524, -0.000, -0.000)], + ["CB", 0, (-0.522, -0.776, -1.213)], + ["O", 3, (0.627, 1.062, -0.000)], + ["CG", 4, (0.607, 1.382, -0.000)], + ["CD1", 5, (0.716, 1.195, -0.000)], + ["CD2", 5, (0.713, -1.194, -0.001)], + ["CE1", 5, (2.107, 1.200, -0.002)], + ["CE2", 5, (2.104, -1.201, -0.003)], + ["OH", 5, (4.168, -0.002, -0.005)], + ["CZ", 5, (2.791, -0.001, -0.003)], + ], + "VAL": [ + ["N", 0, (-0.494, 1.373, -0.000)], + ["CA", 0, (0.000, 0.000, 0.000)], + ["C", 0, (1.527, -0.000, -0.000)], + ["CB", 0, (-0.533, -0.795, -1.213)], + ["O", 3, (0.627, 1.062, -0.000)], + ["CG1", 4, (0.540, 1.429, -0.000)], + ["CG2", 4, (0.533, -0.776, 1.203)], + ], +} + +# A list of atoms (excluding hydrogen) for each AA type. PDB naming convention. +residue_atoms = { + "ALA": ["C", "CA", "CB", "N", "O"], + "ARG": ["C", "CA", "CB", "CG", "CD", "CZ", "N", "NE", "O", "NH1", "NH2"], + "ASP": ["C", "CA", "CB", "CG", "N", "O", "OD1", "OD2"], + "ASN": ["C", "CA", "CB", "CG", "N", "ND2", "O", "OD1"], + "CYS": ["C", "CA", "CB", "N", "O", "SG"], + "GLU": ["C", "CA", "CB", "CG", "CD", "N", "O", "OE1", "OE2"], + "GLN": ["C", "CA", "CB", "CG", "CD", "N", "NE2", "O", "OE1"], + "GLY": ["C", "CA", "N", "O"], + "HIS": ["C", "CA", "CB", "CG", "CD2", "CE1", "N", "ND1", "NE2", "O"], + "ILE": ["C", "CA", "CB", "CG1", "CG2", "CD1", "N", "O"], + "LEU": ["C", "CA", "CB", "CG", "CD1", "CD2", "N", "O"], + "LYS": ["C", "CA", "CB", "CG", "CD", "CE", "N", "NZ", "O"], + "MET": ["C", "CA", "CB", "CG", "CE", "N", "O", "SD"], + "PHE": ["C", "CA", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "N", "O"], + "PRO": ["C", "CA", "CB", "CG", "CD", "N", "O"], + "SER": ["C", "CA", "CB", "N", "O", "OG"], + "THR": ["C", "CA", "CB", "CG2", "N", "O", "OG1"], + "TRP": [ + "C", + "CA", + "CB", + "CG", + "CD1", + "CD2", + "CE2", + "CE3", + "CZ2", + "CZ3", + "CH2", + "N", + "NE1", + "O", + ], + "TYR": [ + "C", + "CA", + "CB", + "CG", + "CD1", + "CD2", + "CE1", + "CE2", + "CZ", + "N", + "O", + "OH", + ], + "VAL": ["C", "CA", "CB", "CG1", "CG2", "N", "O"], +} + +# Naming swaps for ambiguous atom names. +# Due to symmetries in the amino acids the naming of atoms is ambiguous in +# 4 of the 20 amino acids. +# (The LDDT paper lists 7 amino acids as ambiguous, but the naming ambiguities +# in LEU, VAL and ARG can be resolved by using the 3d constellations of +# the 'ambiguous' atoms and their neighbours) +# TODO: ^ interpret this +residue_atom_renaming_swaps = { + "ASP": {"OD1": "OD2"}, + "GLU": {"OE1": "OE2"}, + "PHE": {"CD1": "CD2", "CE1": "CE2"}, + "TYR": {"CD1": "CD2", "CE1": "CE2"}, +} + +# Van der Waals radii [Angstroem] of the atoms (from Wikipedia) +van_der_waals_radius = { + "C": 1.7, + "N": 1.55, + "O": 1.52, + "S": 1.8, +} + +Bond = collections.namedtuple( + "Bond", ["atom1_name", "atom2_name", "length", "stddev"] +) +BondAngle = collections.namedtuple( + "BondAngle", + ["atom1_name", "atom2_name", "atom3name", "angle_rad", "stddev"], +) + + +@functools.lru_cache(maxsize=None) +def load_stereo_chemical_props() -> Tuple[ + Mapping[str, List[Bond]], + Mapping[str, List[Bond]], + Mapping[str, List[BondAngle]], +]: + """Load stereo_chemical_props.txt into a nice structure. + + Load literature values for bond lengths and bond angles and translate + bond angles into the length of the opposite edge of the triangle + ("residue_virtual_bonds"). + + Returns: + residue_bonds: dict that maps resname --> list of Bond tuples + residue_virtual_bonds: dict that maps resname --> list of Bond tuples + residue_bond_angles: dict that maps resname --> list of BondAngle tuples + """ + # TODO: this file should be downloaded in a setup script + stereo_chemical_props = resources.read_text("openfold.resources", "stereo_chemical_props.txt") + + lines_iter = iter(stereo_chemical_props.splitlines()) + # Load bond lengths. + residue_bonds = {} + next(lines_iter) # Skip header line. + for line in lines_iter: + if line.strip() == "-": + break + bond, resname, length, stddev = line.split() + atom1, atom2 = bond.split("-") + if resname not in residue_bonds: + residue_bonds[resname] = [] + residue_bonds[resname].append( + Bond(atom1, atom2, float(length), float(stddev)) + ) + residue_bonds["UNK"] = [] + + # Load bond angles. + residue_bond_angles = {} + next(lines_iter) # Skip empty line. + next(lines_iter) # Skip header line. + for line in lines_iter: + if line.strip() == "-": + break + bond, resname, angle_degree, stddev_degree = line.split() + atom1, atom2, atom3 = bond.split("-") + if resname not in residue_bond_angles: + residue_bond_angles[resname] = [] + residue_bond_angles[resname].append( + BondAngle( + atom1, + atom2, + atom3, + float(angle_degree) / 180.0 * np.pi, + float(stddev_degree) / 180.0 * np.pi, + ) + ) + residue_bond_angles["UNK"] = [] + + def make_bond_key(atom1_name, atom2_name): + """Unique key to lookup bonds.""" + return "-".join(sorted([atom1_name, atom2_name])) + + # Translate bond angles into distances ("virtual bonds"). + residue_virtual_bonds = {} + for resname, bond_angles in residue_bond_angles.items(): + # Create a fast lookup dict for bond lengths. + bond_cache = {} + for b in residue_bonds[resname]: + bond_cache[make_bond_key(b.atom1_name, b.atom2_name)] = b + residue_virtual_bonds[resname] = [] + for ba in bond_angles: + bond1 = bond_cache[make_bond_key(ba.atom1_name, ba.atom2_name)] + bond2 = bond_cache[make_bond_key(ba.atom2_name, ba.atom3name)] + + # Compute distance between atom1 and atom3 using the law of cosines + # c^2 = a^2 + b^2 - 2ab*cos(gamma). + gamma = ba.angle_rad + length = np.sqrt( + bond1.length ** 2 + + bond2.length ** 2 + - 2 * bond1.length * bond2.length * np.cos(gamma) + ) + + # Propagation of uncertainty assuming uncorrelated errors. + dl_outer = 0.5 / length + dl_dgamma = ( + 2 * bond1.length * bond2.length * np.sin(gamma) + ) * dl_outer + dl_db1 = ( + 2 * bond1.length - 2 * bond2.length * np.cos(gamma) + ) * dl_outer + dl_db2 = ( + 2 * bond2.length - 2 * bond1.length * np.cos(gamma) + ) * dl_outer + stddev = np.sqrt( + (dl_dgamma * ba.stddev) ** 2 + + (dl_db1 * bond1.stddev) ** 2 + + (dl_db2 * bond2.stddev) ** 2 + ) + residue_virtual_bonds[resname].append( + Bond(ba.atom1_name, ba.atom3name, length, stddev) + ) + + return (residue_bonds, residue_virtual_bonds, residue_bond_angles) + + +# Between-residue bond lengths for general bonds (first element) and for Proline +# (second element). +between_res_bond_length_c_n = [1.329, 1.341] +between_res_bond_length_stddev_c_n = [0.014, 0.016] + +# Between-residue cos_angles. +between_res_cos_angles_c_n_ca = [-0.5203, 0.0353] # degrees: 121.352 +- 2.315 +between_res_cos_angles_ca_c_n = [-0.4473, 0.0311] # degrees: 116.568 +- 1.995 + +# This mapping is used when we need to store atom data in a format that requires +# fixed atom data size for every residue (e.g. a numpy array). +atom_types = [ + "N", + "CA", + "C", + "CB", + "O", + "CG", + "CG1", + "CG2", + "OG", + "OG1", + "SG", + "CD", + "CD1", + "CD2", + "ND1", + "ND2", + "OD1", + "OD2", + "SD", + "CE", + "CE1", + "CE2", + "CE3", + "NE", + "NE1", + "NE2", + "OE1", + "OE2", + "CH2", + "NH1", + "NH2", + "OH", + "CZ", + "CZ2", + "CZ3", + "NZ", + "OXT", +] +atom_order = {atom_type: i for i, atom_type in enumerate(atom_types)} +atom_type_num = len(atom_types) # := 37. + +# A compact atom encoding with 14 columns +# pylint: disable=line-too-long +# pylint: disable=bad-whitespace +restype_name_to_atom14_names = { + "ALA": ["N", "CA", "C", "O", "CB", "", "", "", "", "", "", "", "", ""], + "ARG": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD", + "NE", + "CZ", + "NH1", + "NH2", + "", + "", + "", + ], + "ASN": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "OD1", + "ND2", + "", + "", + "", + "", + "", + "", + ], + "ASP": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "OD1", + "OD2", + "", + "", + "", + "", + "", + "", + ], + "CYS": ["N", "CA", "C", "O", "CB", "SG", "", "", "", "", "", "", "", ""], + "GLN": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD", + "OE1", + "NE2", + "", + "", + "", + "", + "", + ], + "GLU": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD", + "OE1", + "OE2", + "", + "", + "", + "", + "", + ], + "GLY": ["N", "CA", "C", "O", "", "", "", "", "", "", "", "", "", ""], + "HIS": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "ND1", + "CD2", + "CE1", + "NE2", + "", + "", + "", + "", + ], + "ILE": [ + "N", + "CA", + "C", + "O", + "CB", + "CG1", + "CG2", + "CD1", + "", + "", + "", + "", + "", + "", + ], + "LEU": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD1", + "CD2", + "", + "", + "", + "", + "", + "", + ], + "LYS": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD", + "CE", + "NZ", + "", + "", + "", + "", + "", + ], + "MET": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "SD", + "CE", + "", + "", + "", + "", + "", + "", + ], + "PHE": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD1", + "CD2", + "CE1", + "CE2", + "CZ", + "", + "", + "", + ], + "PRO": ["N", "CA", "C", "O", "CB", "CG", "CD", "", "", "", "", "", "", ""], + "SER": ["N", "CA", "C", "O", "CB", "OG", "", "", "", "", "", "", "", ""], + "THR": [ + "N", + "CA", + "C", + "O", + "CB", + "OG1", + "CG2", + "", + "", + "", + "", + "", + "", + "", + ], + "TRP": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD1", + "CD2", + "NE1", + "CE2", + "CE3", + "CZ2", + "CZ3", + "CH2", + ], + "TYR": [ + "N", + "CA", + "C", + "O", + "CB", + "CG", + "CD1", + "CD2", + "CE1", + "CE2", + "CZ", + "OH", + "", + "", + ], + "VAL": [ + "N", + "CA", + "C", + "O", + "CB", + "CG1", + "CG2", + "", + "", + "", + "", + "", + "", + "", + ], + "UNK": ["", "", "", "", "", "", "", "", "", "", "", "", "", ""], +} +# pylint: enable=line-too-long +# pylint: enable=bad-whitespace + + +# This is the standard residue order when coding AA type as a number. +# Reproduce it by taking 3-letter AA codes and sorting them alphabetically. +restypes = [ + "A", + "R", + "N", + "D", + "C", + "Q", + "E", + "G", + "H", + "I", + "L", + "K", + "M", + "F", + "P", + "S", + "T", + "W", + "Y", + "V", +] +restype_order = {restype: i for i, restype in enumerate(restypes)} +restype_num = len(restypes) # := 20. +unk_restype_index = restype_num # Catch-all index for unknown restypes. + +restypes_with_x = restypes + ["X"] +restype_order_with_x = {restype: i for i, restype in enumerate(restypes_with_x)} + + +def sequence_to_onehot( + sequence: str, mapping: Mapping[str, int], map_unknown_to_x: bool = False +) -> np.ndarray: + """Maps the given sequence into a one-hot encoded matrix. + + Args: + sequence: An amino acid sequence. + mapping: A dictionary mapping amino acids to integers. + map_unknown_to_x: If True, any amino acid that is not in the mapping will be + mapped to the unknown amino acid 'X'. If the mapping doesn't contain + amino acid 'X', an error will be thrown. If False, any amino acid not in + the mapping will throw an error. + + Returns: + A numpy array of shape (seq_len, num_unique_aas) with one-hot encoding of + the sequence. + + Raises: + ValueError: If the mapping doesn't contain values from 0 to + num_unique_aas - 1 without any gaps. + """ + num_entries = max(mapping.values()) + 1 + + if sorted(set(mapping.values())) != list(range(num_entries)): + raise ValueError( + "The mapping must have values from 0 to num_unique_aas-1 " + "without any gaps. Got: %s" % sorted(mapping.values()) + ) + + one_hot_arr = np.zeros((len(sequence), num_entries), dtype=int) + + for aa_index, aa_type in enumerate(sequence): + if map_unknown_to_x: + if aa_type.isalpha() and aa_type.isupper(): + aa_id = mapping.get(aa_type, mapping["X"]) + else: + raise ValueError( + f"Invalid character in the sequence: {aa_type}" + ) + else: + aa_id = mapping[aa_type] + one_hot_arr[aa_index, aa_id] = 1 + + return one_hot_arr + + +restype_1to3 = { + "A": "ALA", + "R": "ARG", + "N": "ASN", + "D": "ASP", + "C": "CYS", + "Q": "GLN", + "E": "GLU", + "G": "GLY", + "H": "HIS", + "I": "ILE", + "L": "LEU", + "K": "LYS", + "M": "MET", + "F": "PHE", + "P": "PRO", + "S": "SER", + "T": "THR", + "W": "TRP", + "Y": "TYR", + "V": "VAL", +} + + +# NB: restype_3to1 differs from Bio.PDB.protein_letters_3to1 by being a simple +# 1-to-1 mapping of 3 letter names to one letter names. The latter contains +# many more, and less common, three letter names as keys and maps many of these +# to the same one letter name (including 'X' and 'U' which we don't use here). +restype_3to1 = {v: k for k, v in restype_1to3.items()} + +# Define a restype name for all unknown residues. +unk_restype = "UNK" + +resnames = [restype_1to3[r] for r in restypes] + [unk_restype] +resname_to_idx = {resname: i for i, resname in enumerate(resnames)} + + +# The mapping here uses hhblits convention, so that B is mapped to D, J and O +# are mapped to X, U is mapped to C, and Z is mapped to E. Other than that the +# remaining 20 amino acids are kept in alphabetical order. +# There are 2 non-amino acid codes, X (representing any amino acid) and +# "-" representing a missing amino acid in an alignment. The id for these +# codes is put at the end (20 and 21) so that they can easily be ignored if +# desired. +HHBLITS_AA_TO_ID = { + "A": 0, + "B": 2, + "C": 1, + "D": 2, + "E": 3, + "F": 4, + "G": 5, + "H": 6, + "I": 7, + "J": 20, + "K": 8, + "L": 9, + "M": 10, + "N": 11, + "O": 20, + "P": 12, + "Q": 13, + "R": 14, + "S": 15, + "T": 16, + "U": 1, + "V": 17, + "W": 18, + "X": 20, + "Y": 19, + "Z": 3, + "-": 21, +} + +# Partial inversion of HHBLITS_AA_TO_ID. +ID_TO_HHBLITS_AA = { + 0: "A", + 1: "C", # Also U. + 2: "D", # Also B. + 3: "E", # Also Z. + 4: "F", + 5: "G", + 6: "H", + 7: "I", + 8: "K", + 9: "L", + 10: "M", + 11: "N", + 12: "P", + 13: "Q", + 14: "R", + 15: "S", + 16: "T", + 17: "V", + 18: "W", + 19: "Y", + 20: "X", # Includes J and O. + 21: "-", +} + +restypes_with_x_and_gap = restypes + ["X", "-"] +MAP_HHBLITS_AATYPE_TO_OUR_AATYPE = tuple( + restypes_with_x_and_gap.index(ID_TO_HHBLITS_AA[i]) + for i in range(len(restypes_with_x_and_gap)) +) + + +def _make_standard_atom_mask() -> np.ndarray: + """Returns [num_res_types, num_atom_types] mask array.""" + # +1 to account for unknown (all 0s). + mask = np.zeros([restype_num + 1, atom_type_num], dtype=int) + for restype, restype_letter in enumerate(restypes): + restype_name = restype_1to3[restype_letter] + atom_names = residue_atoms[restype_name] + for atom_name in atom_names: + atom_type = atom_order[atom_name] + mask[restype, atom_type] = 1 + return mask + + +STANDARD_ATOM_MASK = _make_standard_atom_mask() + + +# A one hot representation for the first and second atoms defining the axis +# of rotation for each chi-angle in each residue. +def chi_angle_atom(atom_index: int) -> np.ndarray: + """Define chi-angle rigid groups via one-hot representations.""" + chi_angles_index = {} + one_hots = [] + + for k, v in chi_angles_atoms.items(): + indices = [atom_types.index(s[atom_index]) for s in v] + indices.extend([-1] * (4 - len(indices))) + chi_angles_index[k] = indices + + for r in restypes: + res3 = restype_1to3[r] + one_hot = np.eye(atom_type_num)[chi_angles_index[res3]] + one_hots.append(one_hot) + + one_hots.append(np.zeros([4, atom_type_num])) # Add zeros for residue `X`. + one_hot = np.stack(one_hots, axis=0) + one_hot = np.transpose(one_hot, [0, 2, 1]) + + return one_hot + + +chi_atom_1_one_hot = chi_angle_atom(1) +chi_atom_2_one_hot = chi_angle_atom(2) + +# An array like chi_angles_atoms but using indices rather than names. +chi_angles_atom_indices = [chi_angles_atoms[restype_1to3[r]] for r in restypes] +chi_angles_atom_indices = tree.map_structure( + lambda atom_name: atom_order[atom_name], chi_angles_atom_indices +) +chi_angles_atom_indices = np.array( + [ + chi_atoms + ([[0, 0, 0, 0]] * (4 - len(chi_atoms))) + for chi_atoms in chi_angles_atom_indices + ] +) + +# Mapping from (res_name, atom_name) pairs to the atom's chi group index +# and atom index within that group. +chi_groups_for_atom = collections.defaultdict(list) +for res_name, chi_angle_atoms_for_res in chi_angles_atoms.items(): + for chi_group_i, chi_group in enumerate(chi_angle_atoms_for_res): + for atom_i, atom in enumerate(chi_group): + chi_groups_for_atom[(res_name, atom)].append((chi_group_i, atom_i)) +chi_groups_for_atom = dict(chi_groups_for_atom) + + +def _make_rigid_transformation_4x4(ex, ey, translation): + """Create a rigid 4x4 transformation matrix from two axes and transl.""" + # Normalize ex. + ex_normalized = ex / np.linalg.norm(ex) + + # make ey perpendicular to ex + ey_normalized = ey - np.dot(ey, ex_normalized) * ex_normalized + ey_normalized /= np.linalg.norm(ey_normalized) + + # compute ez as cross product + eznorm = np.cross(ex_normalized, ey_normalized) + m = np.stack( + [ex_normalized, ey_normalized, eznorm, translation] + ).transpose() + m = np.concatenate([m, [[0.0, 0.0, 0.0, 1.0]]], axis=0) + return m + + +# create an array with (restype, atomtype) --> rigid_group_idx +# and an array with (restype, atomtype, coord) for the atom positions +# and compute affine transformation matrices (4,4) from one rigid group to the +# previous group +restype_atom37_to_rigid_group = np.zeros([21, 37], dtype=int) +restype_atom37_mask = np.zeros([21, 37], dtype=np.float32) +restype_atom37_rigid_group_positions = np.zeros([21, 37, 3], dtype=np.float32) +restype_atom14_to_rigid_group = np.zeros([21, 14], dtype=int) +restype_atom14_mask = np.zeros([21, 14], dtype=np.float32) +restype_atom14_rigid_group_positions = np.zeros([21, 14, 3], dtype=np.float32) +restype_rigid_group_default_frame = np.zeros([21, 8, 4, 4], dtype=np.float32) + + +def _make_rigid_group_constants(): + """Fill the arrays above.""" + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + for atomname, group_idx, atom_position in rigid_group_atom_positions[ + resname + ]: + atomtype = atom_order[atomname] + restype_atom37_to_rigid_group[restype, atomtype] = group_idx + restype_atom37_mask[restype, atomtype] = 1 + restype_atom37_rigid_group_positions[ + restype, atomtype, : + ] = atom_position + + atom14idx = restype_name_to_atom14_names[resname].index(atomname) + restype_atom14_to_rigid_group[restype, atom14idx] = group_idx + restype_atom14_mask[restype, atom14idx] = 1 + restype_atom14_rigid_group_positions[ + restype, atom14idx, : + ] = atom_position + + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + atom_positions = { + name: np.array(pos) + for name, _, pos in rigid_group_atom_positions[resname] + } + + # backbone to backbone is the identity transform + restype_rigid_group_default_frame[restype, 0, :, :] = np.eye(4) + + # pre-omega-frame to backbone (currently dummy identity matrix) + restype_rigid_group_default_frame[restype, 1, :, :] = np.eye(4) + + # phi-frame to backbone + mat = _make_rigid_transformation_4x4( + ex=atom_positions["N"] - atom_positions["CA"], + ey=np.array([1.0, 0.0, 0.0]), + translation=atom_positions["N"], + ) + restype_rigid_group_default_frame[restype, 2, :, :] = mat + + # psi-frame to backbone + mat = _make_rigid_transformation_4x4( + ex=atom_positions["C"] - atom_positions["CA"], + ey=atom_positions["CA"] - atom_positions["N"], + translation=atom_positions["C"], + ) + restype_rigid_group_default_frame[restype, 3, :, :] = mat + + # chi1-frame to backbone + if chi_angles_mask[restype][0]: + base_atom_names = chi_angles_atoms[resname][0] + base_atom_positions = [ + atom_positions[name] for name in base_atom_names + ] + mat = _make_rigid_transformation_4x4( + ex=base_atom_positions[2] - base_atom_positions[1], + ey=base_atom_positions[0] - base_atom_positions[1], + translation=base_atom_positions[2], + ) + restype_rigid_group_default_frame[restype, 4, :, :] = mat + + # chi2-frame to chi1-frame + # chi3-frame to chi2-frame + # chi4-frame to chi3-frame + # luckily all rotation axes for the next frame start at (0,0,0) of the + # previous frame + for chi_idx in range(1, 4): + if chi_angles_mask[restype][chi_idx]: + axis_end_atom_name = chi_angles_atoms[resname][chi_idx][2] + axis_end_atom_position = atom_positions[axis_end_atom_name] + mat = _make_rigid_transformation_4x4( + ex=axis_end_atom_position, + ey=np.array([-1.0, 0.0, 0.0]), + translation=axis_end_atom_position, + ) + restype_rigid_group_default_frame[ + restype, 4 + chi_idx, :, : + ] = mat + + +_make_rigid_group_constants() + + +def make_atom14_dists_bounds( + overlap_tolerance=1.5, bond_length_tolerance_factor=15 +): + """compute upper and lower bounds for bonds to assess violations.""" + restype_atom14_bond_lower_bound = np.zeros([21, 14, 14], np.float32) + restype_atom14_bond_upper_bound = np.zeros([21, 14, 14], np.float32) + restype_atom14_bond_stddev = np.zeros([21, 14, 14], np.float32) + residue_bonds, residue_virtual_bonds, _ = load_stereo_chemical_props() + for restype, restype_letter in enumerate(restypes): + resname = restype_1to3[restype_letter] + atom_list = restype_name_to_atom14_names[resname] + + # create lower and upper bounds for clashes + for atom1_idx, atom1_name in enumerate(atom_list): + if not atom1_name: + continue + atom1_radius = van_der_waals_radius[atom1_name[0]] + for atom2_idx, atom2_name in enumerate(atom_list): + if (not atom2_name) or atom1_idx == atom2_idx: + continue + atom2_radius = van_der_waals_radius[atom2_name[0]] + lower = atom1_radius + atom2_radius - overlap_tolerance + upper = 1e10 + restype_atom14_bond_lower_bound[ + restype, atom1_idx, atom2_idx + ] = lower + restype_atom14_bond_lower_bound[ + restype, atom2_idx, atom1_idx + ] = lower + restype_atom14_bond_upper_bound[ + restype, atom1_idx, atom2_idx + ] = upper + restype_atom14_bond_upper_bound[ + restype, atom2_idx, atom1_idx + ] = upper + + # overwrite lower and upper bounds for bonds and angles + for b in residue_bonds[resname] + residue_virtual_bonds[resname]: + atom1_idx = atom_list.index(b.atom1_name) + atom2_idx = atom_list.index(b.atom2_name) + lower = b.length - bond_length_tolerance_factor * b.stddev + upper = b.length + bond_length_tolerance_factor * b.stddev + restype_atom14_bond_lower_bound[ + restype, atom1_idx, atom2_idx + ] = lower + restype_atom14_bond_lower_bound[ + restype, atom2_idx, atom1_idx + ] = lower + restype_atom14_bond_upper_bound[ + restype, atom1_idx, atom2_idx + ] = upper + restype_atom14_bond_upper_bound[ + restype, atom2_idx, atom1_idx + ] = upper + restype_atom14_bond_stddev[restype, atom1_idx, atom2_idx] = b.stddev + restype_atom14_bond_stddev[restype, atom2_idx, atom1_idx] = b.stddev + return { + "lower_bound": restype_atom14_bond_lower_bound, # shape (21,14,14) + "upper_bound": restype_atom14_bond_upper_bound, # shape (21,14,14) + "stddev": restype_atom14_bond_stddev, # shape (21,14,14) + } + + +restype_atom14_ambiguous_atoms = np.zeros((21, 14), dtype=np.float32) +restype_atom14_ambiguous_atoms_swap_idx = np.tile( + np.arange(14, dtype=int), (21, 1) +) + + +def _make_atom14_ambiguity_feats(): + for res, pairs in residue_atom_renaming_swaps.items(): + res_idx = restype_order[restype_3to1[res]] + for atom1, atom2 in pairs.items(): + atom1_idx = restype_name_to_atom14_names[res].index(atom1) + atom2_idx = restype_name_to_atom14_names[res].index(atom2) + restype_atom14_ambiguous_atoms[res_idx, atom1_idx] = 1 + restype_atom14_ambiguous_atoms[res_idx, atom2_idx] = 1 + restype_atom14_ambiguous_atoms_swap_idx[ + res_idx, atom1_idx + ] = atom2_idx + restype_atom14_ambiguous_atoms_swap_idx[ + res_idx, atom2_idx + ] = atom1_idx + + +_make_atom14_ambiguity_feats() + + +def aatype_to_str_sequence(aatype): + return ''.join([ + restypes_with_x[aatype[i]] + for i in range(len(aatype)) + ]) diff --git a/gafl/openfold/resources/__init__.py b/gafl/openfold/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gafl/openfold/utils/__pycache__/rigid_utils.cpython-310.pyc b/gafl/openfold/utils/__pycache__/rigid_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69f318e7a0c1408b22eb598dbf43e206ff5ee407 Binary files /dev/null and b/gafl/openfold/utils/__pycache__/rigid_utils.cpython-310.pyc differ diff --git a/gafl/openfold/utils/__pycache__/rigid_utils.cpython-311.pyc b/gafl/openfold/utils/__pycache__/rigid_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7159ea3c5da5040b410fd4cd02abb01134aabc Binary files /dev/null and b/gafl/openfold/utils/__pycache__/rigid_utils.cpython-311.pyc differ diff --git a/gafl/openfold/utils/__pycache__/tensor_utils.cpython-310.pyc b/gafl/openfold/utils/__pycache__/tensor_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86aa977d18b5983847e8f580e804a054021931f1 Binary files /dev/null and b/gafl/openfold/utils/__pycache__/tensor_utils.cpython-310.pyc differ diff --git a/gafl/openfold/utils/__pycache__/tensor_utils.cpython-311.pyc b/gafl/openfold/utils/__pycache__/tensor_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5aa6724e119d3ebae813e5a281642bb94043b2c Binary files /dev/null and b/gafl/openfold/utils/__pycache__/tensor_utils.cpython-311.pyc differ diff --git a/gafl/openfold/utils/argparse.py b/gafl/openfold/utils/argparse.py new file mode 100644 index 0000000000000000000000000000000000000000..d13f895ec418ef74af1c1ffd7ec227cdd691236f --- /dev/null +++ b/gafl/openfold/utils/argparse.py @@ -0,0 +1,30 @@ +from argparse import HelpFormatter +from operator import attrgetter + +class ArgparseAlphabetizer(HelpFormatter): + """ + Sorts the optional arguments of an argparse parser alphabetically + """ + + @staticmethod + def sort_actions(actions): + return sorted(actions, key=attrgetter("option_strings")) + + # Formats the help message + def add_arguments(self, actions): + actions = ArgparseAlphabetizer.sort_actions(actions) + super(ArgparseAlphabetizer, self).add_arguments(actions) + + # Formats the usage message + def add_usage(self, usage, actions, groups, prefix=None): + actions = ArgparseAlphabetizer.sort_actions(actions) + args = usage, actions, groups, prefix + super(ArgparseAlphabetizer, self).add_usage(*args) + + +def remove_arguments(parser, args): + for arg in args: + for action in parser._actions: + opts = vars(action)["option_strings"] + if(arg in opts): + parser._handle_conflict_resolve(None, [(arg, action)]) diff --git a/gafl/openfold/utils/callbacks.py b/gafl/openfold/utils/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..872dbdce98bcca08e58368481c05024986b4a71f --- /dev/null +++ b/gafl/openfold/utils/callbacks.py @@ -0,0 +1,14 @@ +from pytorch_lightning.utilities import rank_zero_info +from pytorch_lightning.callbacks.early_stopping import EarlyStopping + +class EarlyStoppingVerbose(EarlyStopping): + """ + The default EarlyStopping callback's verbose mode is too verbose. + This class outputs a message only when it's getting ready to stop. + """ + def _evalute_stopping_criteria(self, *args): + should_stop, reason = super()._evalute_stopping_criteria(*args) + if(should_stop): + rank_zero_info(f"{reason}\n") + + return should_stop, reason diff --git a/gafl/openfold/utils/checkpointing.py b/gafl/openfold/utils/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..75a4455ae6b1581d76dab7bcf3adf590e9be15df --- /dev/null +++ b/gafl/openfold/utils/checkpointing.py @@ -0,0 +1,88 @@ +# Copyright 2021 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import deepspeed +import torch +import torch.utils.checkpoint +from typing import Any, Tuple, List, Callable, Optional + + +BLOCK_ARG = Any +BLOCK_ARGS = List[BLOCK_ARG] + + +def get_checkpoint_fn(): + if(deepspeed.checkpointing.is_configured()): + checkpoint = deepspeed.checkpointing.checkpoint + else: + checkpoint = torch.utils.checkpoint.checkpoint + + return checkpoint + + +@torch.jit.ignore +def checkpoint_blocks( + blocks: List[Callable], + args: BLOCK_ARGS, + blocks_per_ckpt: Optional[int], +) -> BLOCK_ARGS: + """ + Chunk a list of blocks and run each chunk with activation + checkpointing. We define a "block" as a callable whose only inputs are + the outputs of the previous block. + + Implements Subsection 1.11.8 + + Args: + blocks: + List of blocks + args: + Tuple of arguments for the first block. + blocks_per_ckpt: + Size of each chunk. A higher value corresponds to fewer + checkpoints, and trades memory for speed. If None, no checkpointing + is performed. + Returns: + The output of the final block + """ + def wrap(a): + return (a,) if type(a) is not tuple else a + + def exec(b, a): + for block in b: + a = wrap(block(*a)) + return a + + def chunker(s, e): + def exec_sliced(*a): + return exec(blocks[s:e], a) + + return exec_sliced + + # Avoids mishaps when the blocks take just one argument + args = wrap(args) + + if blocks_per_ckpt is None: + return exec(blocks, args) + elif blocks_per_ckpt < 1 or blocks_per_ckpt > len(blocks): + raise ValueError("blocks_per_ckpt must be between 1 and len(blocks)") + + checkpoint = get_checkpoint_fn() + + for s in range(0, len(blocks), blocks_per_ckpt): + e = s + blocks_per_ckpt + args = checkpoint(chunker(s, e), *args) + args = wrap(args) + + return args \ No newline at end of file diff --git a/gafl/openfold/utils/exponential_moving_average.py b/gafl/openfold/utils/exponential_moving_average.py new file mode 100644 index 0000000000000000000000000000000000000000..53649506a7af46c7530687c14c79c2cb8d43c089 --- /dev/null +++ b/gafl/openfold/utils/exponential_moving_average.py @@ -0,0 +1,70 @@ +from collections import OrderedDict +import copy +import torch +import torch.nn as nn + +from openfold.utils.tensor_utils import tensor_tree_map + + +class ExponentialMovingAverage: + """ + Maintains moving averages of parameters with exponential decay + + At each step, the stored copy `copy` of each parameter `param` is + updated as follows: + + `copy = decay * copy + (1 - decay) * param` + + where `decay` is an attribute of the ExponentialMovingAverage object. + """ + + def __init__(self, model: nn.Module, decay: float): + """ + Args: + model: + A torch.nn.Module whose parameters are to be tracked + decay: + A value (usually close to 1.) by which updates are + weighted as part of the above formula + """ + super(ExponentialMovingAverage, self).__init__() + + clone_param = lambda t: t.clone().detach() + self.params = tensor_tree_map(clone_param, model.state_dict()) + self.decay = decay + self.device = next(model.parameters()).device + + def to(self, device): + self.params = tensor_tree_map(lambda t: t.to(device), self.params) + self.device = device + + def _update_state_dict_(self, update, state_dict): + with torch.no_grad(): + for k, v in update.items(): + stored = state_dict[k] + if not isinstance(v, torch.Tensor): + self._update_state_dict_(v, stored) + else: + diff = stored - v + diff *= 1 - self.decay + stored -= diff + + def update(self, model: torch.nn.Module) -> None: + """ + Updates the stored parameters using the state dict of the provided + module. The module should have the same structure as that used to + initialize the ExponentialMovingAverage object. + """ + self._update_state_dict_(model.state_dict(), self.params) + + def load_state_dict(self, state_dict: OrderedDict) -> None: + self.params = state_dict["params"] + self.decay = state_dict["decay"] + + def state_dict(self) -> OrderedDict: + return OrderedDict( + { + "params": self.params, + "decay": self.decay, + } + ) diff --git a/gafl/openfold/utils/feats.py b/gafl/openfold/utils/feats.py new file mode 100644 index 0000000000000000000000000000000000000000..3be298ff4cfd578d446142826937b5643551db29 --- /dev/null +++ b/gafl/openfold/utils/feats.py @@ -0,0 +1,267 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math + +import numpy as np +import torch +import torch.nn as nn +from typing import Dict + +from openfold.np import protein +import openfold.np.residue_constants as rc +from openfold.utils.rigid_utils import Rotation, Rigid +from openfold.utils.tensor_utils import ( + batched_gather, + one_hot, + tree_map, + tensor_tree_map, +) + + +def pseudo_beta_fn(aatype, all_atom_positions, all_atom_masks): + is_gly = aatype == rc.restype_order["G"] + ca_idx = rc.atom_order["CA"] + cb_idx = rc.atom_order["CB"] + pseudo_beta = torch.where( + is_gly[..., None].expand(*((-1,) * len(is_gly.shape)), 3), + all_atom_positions[..., ca_idx, :], + all_atom_positions[..., cb_idx, :], + ) + + if all_atom_masks is not None: + pseudo_beta_mask = torch.where( + is_gly, + all_atom_masks[..., ca_idx], + all_atom_masks[..., cb_idx], + ) + return pseudo_beta, pseudo_beta_mask + else: + return pseudo_beta + + +def atom14_to_atom37(atom14, batch): + atom37_data = batched_gather( + atom14, + batch["residx_atom37_to_atom14"], + dim=-2, + no_batch_dims=len(atom14.shape[:-2]), + ) + + atom37_data = atom37_data * batch["atom37_atom_exists"][..., None] + + return atom37_data + + +def build_template_angle_feat(template_feats): + template_aatype = template_feats["template_aatype"] + torsion_angles_sin_cos = template_feats["template_torsion_angles_sin_cos"] + alt_torsion_angles_sin_cos = template_feats[ + "template_alt_torsion_angles_sin_cos" + ] + torsion_angles_mask = template_feats["template_torsion_angles_mask"] + template_angle_feat = torch.cat( + [ + nn.functional.one_hot(template_aatype, 22), + torsion_angles_sin_cos.reshape( + *torsion_angles_sin_cos.shape[:-2], 14 + ), + alt_torsion_angles_sin_cos.reshape( + *alt_torsion_angles_sin_cos.shape[:-2], 14 + ), + torsion_angles_mask, + ], + dim=-1, + ) + + return template_angle_feat + + +def build_template_pair_feat( + batch, min_bin, max_bin, no_bins, eps=1e-20, inf=1e8 +): + template_mask = batch["template_pseudo_beta_mask"] + template_mask_2d = template_mask[..., None] * template_mask[..., None, :] + + # Compute distogram (this seems to differ slightly from Alg. 5) + tpb = batch["template_pseudo_beta"] + dgram = torch.sum( + (tpb[..., None, :] - tpb[..., None, :, :]) ** 2, dim=-1, keepdim=True + ) + lower = torch.linspace(min_bin, max_bin, no_bins, device=tpb.device) ** 2 + upper = torch.cat([lower[:-1], lower.new_tensor([inf])], dim=-1) + dgram = ((dgram > lower) * (dgram < upper)).type(dgram.dtype) + + to_concat = [dgram, template_mask_2d[..., None]] + + aatype_one_hot = nn.functional.one_hot( + batch["template_aatype"], + rc.restype_num + 2, + ) + + n_res = batch["template_aatype"].shape[-1] + to_concat.append( + aatype_one_hot[..., None, :, :].expand( + *aatype_one_hot.shape[:-2], n_res, -1, -1 + ) + ) + to_concat.append( + aatype_one_hot[..., None, :].expand( + *aatype_one_hot.shape[:-2], -1, n_res, -1 + ) + ) + + n, ca, c = [rc.atom_order[a] for a in ["N", "CA", "C"]] + rigids = Rigid.make_transform_from_reference( + n_xyz=batch["template_all_atom_positions"][..., n, :], + ca_xyz=batch["template_all_atom_positions"][..., ca, :], + c_xyz=batch["template_all_atom_positions"][..., c, :], + eps=eps, + ) + points = rigids.get_trans()[..., None, :, :] + rigid_vec = rigids[..., None].invert_apply(points) + + inv_distance_scalar = torch.rsqrt(eps + torch.sum(rigid_vec ** 2, dim=-1)) + + t_aa_masks = batch["template_all_atom_mask"] + template_mask = ( + t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c] + ) + template_mask_2d = template_mask[..., None] * template_mask[..., None, :] + + inv_distance_scalar = inv_distance_scalar * template_mask_2d + unit_vector = rigid_vec * inv_distance_scalar[..., None] + to_concat.extend(torch.unbind(unit_vector[..., None, :], dim=-1)) + to_concat.append(template_mask_2d[..., None]) + + act = torch.cat(to_concat, dim=-1) + act = act * template_mask_2d[..., None] + + return act + + +def build_extra_msa_feat(batch): + msa_1hot = nn.functional.one_hot(batch["extra_msa"], 23) + msa_feat = [ + msa_1hot, + batch["extra_has_deletion"].unsqueeze(-1), + batch["extra_deletion_value"].unsqueeze(-1), + ] + return torch.cat(msa_feat, dim=-1) + + +def torsion_angles_to_frames( + r: Rigid, + alpha: torch.Tensor, + aatype: torch.Tensor, + rrgdf: torch.Tensor, +): + # [*, N, 8, 4, 4] + default_4x4 = rrgdf[aatype, ...] + + # [*, N, 8] transformations, i.e. + # One [*, N, 8, 3, 3] rotation matrix and + # One [*, N, 8, 3] translation matrix + default_r = r.from_tensor_4x4(default_4x4) + + bb_rot = alpha.new_zeros((*((1,) * len(alpha.shape[:-1])), 2)) + bb_rot[..., 1] = 1 + + # [*, N, 8, 2] + alpha = torch.cat( + [bb_rot.expand(*alpha.shape[:-2], -1, -1), alpha], dim=-2 + ) + + # [*, N, 8, 3, 3] + # Produces rotation matrices of the form: + # [ + # [1, 0 , 0 ], + # [0, a_2,-a_1], + # [0, a_1, a_2] + # ] + # This follows the original code rather than the supplement, which uses + # different indices. + + all_rots = alpha.new_zeros(default_r.get_rots().get_rot_mats().shape) + all_rots[..., 0, 0] = 1 + all_rots[..., 1, 1] = alpha[..., 1] + all_rots[..., 1, 2] = -alpha[..., 0] + all_rots[..., 2, 1:] = alpha + + all_rots = Rigid(Rotation(rot_mats=all_rots), None) + + all_frames = default_r.compose(all_rots) + + chi2_frame_to_frame = all_frames[..., 5] + chi3_frame_to_frame = all_frames[..., 6] + chi4_frame_to_frame = all_frames[..., 7] + + chi1_frame_to_bb = all_frames[..., 4] + chi2_frame_to_bb = chi1_frame_to_bb.compose(chi2_frame_to_frame) + chi3_frame_to_bb = chi2_frame_to_bb.compose(chi3_frame_to_frame) + chi4_frame_to_bb = chi3_frame_to_bb.compose(chi4_frame_to_frame) + + all_frames_to_bb = Rigid.cat( + [ + all_frames[..., :5], + chi2_frame_to_bb.unsqueeze(-1), + chi3_frame_to_bb.unsqueeze(-1), + chi4_frame_to_bb.unsqueeze(-1), + ], + dim=-1, + ) + + all_frames_to_global = r[..., None].compose(all_frames_to_bb) + + return all_frames_to_global + + +def frames_and_literature_positions_to_atom14_pos( + r: Rigid, + aatype: torch.Tensor, + default_frames, + group_idx, + atom_mask, + lit_positions, +): + # [*, N, 14, 4, 4] + default_4x4 = default_frames[aatype, ...] + + # [*, N, 14] + group_mask = group_idx[aatype, ...] + + # [*, N, 14, 8] + group_mask = nn.functional.one_hot( + group_mask, + num_classes=default_frames.shape[-3], + ) + + # [*, N, 14, 8] + t_atoms_to_global = r[..., None, :] * group_mask + + # [*, N, 14] + t_atoms_to_global = t_atoms_to_global.map_tensor_fn( + lambda x: torch.sum(x, dim=-1) + ) + + # [*, N, 14, 1] + atom_mask = atom_mask[aatype, ...].unsqueeze(-1) + + # [*, N, 14, 3] + lit_positions = lit_positions[aatype, ...] + pred_positions = t_atoms_to_global.apply(lit_positions) + pred_positions = pred_positions * atom_mask + + return pred_positions diff --git a/gafl/openfold/utils/import_weights.py b/gafl/openfold/utils/import_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1ebd6d6adc6d60e9dadbb04c677db013cb7f3a --- /dev/null +++ b/gafl/openfold/utils/import_weights.py @@ -0,0 +1,449 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from enum import Enum +from dataclasses import dataclass +from functools import partial +import numpy as np +import torch +from typing import Union, List + + +_NPZ_KEY_PREFIX = "alphafold/alphafold_iteration/" + + +# With Param, a poor man's enum with attributes (Rust-style) +class ParamType(Enum): + LinearWeight = partial( # hack: partial prevents fns from becoming methods + lambda w: w.transpose(-1, -2) + ) + LinearWeightMHA = partial( + lambda w: w.reshape(*w.shape[:-2], -1).transpose(-1, -2) + ) + LinearMHAOutputWeight = partial( + lambda w: w.reshape(*w.shape[:-3], -1, w.shape[-1]).transpose(-1, -2) + ) + LinearBiasMHA = partial(lambda w: w.reshape(*w.shape[:-2], -1)) + LinearWeightOPM = partial( + lambda w: w.reshape(*w.shape[:-3], -1, w.shape[-1]).transpose(-1, -2) + ) + Other = partial(lambda w: w) + + def __init__(self, fn): + self.transformation = fn + + +@dataclass +class Param: + param: Union[torch.Tensor, List[torch.Tensor]] + param_type: ParamType = ParamType.Other + stacked: bool = False + + +def _process_translations_dict(d, top_layer=True): + flat = {} + for k, v in d.items(): + if type(v) == dict: + prefix = _NPZ_KEY_PREFIX if top_layer else "" + sub_flat = { + (prefix + "/".join([k, k_prime])): v_prime + for k_prime, v_prime in _process_translations_dict( + v, top_layer=False + ).items() + } + flat.update(sub_flat) + else: + k = "/" + k if not top_layer else k + flat[k] = v + + return flat + + +def stacked(param_dict_list, out=None): + """ + Args: + param_dict_list: + A list of (nested) Param dicts to stack. The structure of + each dict must be the identical (down to the ParamTypes of + "parallel" Params). There must be at least one dict + in the list. + """ + if out is None: + out = {} + template = param_dict_list[0] + for k, _ in template.items(): + v = [d[k] for d in param_dict_list] + if type(v[0]) is dict: + out[k] = {} + stacked(v, out=out[k]) + elif type(v[0]) is Param: + stacked_param = Param( + param=[param.param for param in v], + param_type=v[0].param_type, + stacked=True, + ) + + out[k] = stacked_param + + return out + + +def assign(translation_dict, orig_weights): + for k, param in translation_dict.items(): + with torch.no_grad(): + weights = torch.as_tensor(orig_weights[k]) + ref, param_type = param.param, param.param_type + if param.stacked: + weights = torch.unbind(weights, 0) + else: + weights = [weights] + ref = [ref] + + try: + weights = list(map(param_type.transformation, weights)) + for p, w in zip(ref, weights): + p.copy_(w) + except: + print(k) + print(ref[0].shape) + print(weights[0].shape) + raise + + +def import_jax_weights_(model, npz_path, version="model_1"): + data = np.load(npz_path) + + ####################### + # Some templates + ####################### + + LinearWeight = lambda l: (Param(l, param_type=ParamType.LinearWeight)) + + LinearBias = lambda l: (Param(l)) + + LinearWeightMHA = lambda l: (Param(l, param_type=ParamType.LinearWeightMHA)) + + LinearBiasMHA = lambda b: (Param(b, param_type=ParamType.LinearBiasMHA)) + + LinearWeightOPM = lambda l: (Param(l, param_type=ParamType.LinearWeightOPM)) + + LinearParams = lambda l: { + "weights": LinearWeight(l.weight), + "bias": LinearBias(l.bias), + } + + LayerNormParams = lambda l: { + "scale": Param(l.weight), + "offset": Param(l.bias), + } + + AttentionParams = lambda att: { + "query_w": LinearWeightMHA(att.linear_q.weight), + "key_w": LinearWeightMHA(att.linear_k.weight), + "value_w": LinearWeightMHA(att.linear_v.weight), + "output_w": Param( + att.linear_o.weight, + param_type=ParamType.LinearMHAOutputWeight, + ), + "output_b": LinearBias(att.linear_o.bias), + } + + AttentionGatedParams = lambda att: dict( + **AttentionParams(att), + **{ + "gating_w": LinearWeightMHA(att.linear_g.weight), + "gating_b": LinearBiasMHA(att.linear_g.bias), + }, + ) + + GlobalAttentionParams = lambda att: dict( + AttentionGatedParams(att), + key_w=LinearWeight(att.linear_k.weight), + value_w=LinearWeight(att.linear_v.weight), + ) + + TriAttParams = lambda tri_att: { + "query_norm": LayerNormParams(tri_att.layer_norm), + "feat_2d_weights": LinearWeight(tri_att.linear.weight), + "attention": AttentionGatedParams(tri_att.mha), + } + + TriMulOutParams = lambda tri_mul: { + "layer_norm_input": LayerNormParams(tri_mul.layer_norm_in), + "left_projection": LinearParams(tri_mul.linear_a_p), + "right_projection": LinearParams(tri_mul.linear_b_p), + "left_gate": LinearParams(tri_mul.linear_a_g), + "right_gate": LinearParams(tri_mul.linear_b_g), + "center_layer_norm": LayerNormParams(tri_mul.layer_norm_out), + "output_projection": LinearParams(tri_mul.linear_z), + "gating_linear": LinearParams(tri_mul.linear_g), + } + + # see commit b88f8da on the Alphafold repo + # Alphafold swaps the pseudocode's a and b between the incoming/outcoming + # iterations of triangle multiplication, which is confusing and not + # reproduced in our implementation. + TriMulInParams = lambda tri_mul: { + "layer_norm_input": LayerNormParams(tri_mul.layer_norm_in), + "left_projection": LinearParams(tri_mul.linear_b_p), + "right_projection": LinearParams(tri_mul.linear_a_p), + "left_gate": LinearParams(tri_mul.linear_b_g), + "right_gate": LinearParams(tri_mul.linear_a_g), + "center_layer_norm": LayerNormParams(tri_mul.layer_norm_out), + "output_projection": LinearParams(tri_mul.linear_z), + "gating_linear": LinearParams(tri_mul.linear_g), + } + + PairTransitionParams = lambda pt: { + "input_layer_norm": LayerNormParams(pt.layer_norm), + "transition1": LinearParams(pt.linear_1), + "transition2": LinearParams(pt.linear_2), + } + + MSAAttParams = lambda matt: { + "query_norm": LayerNormParams(matt.layer_norm_m), + "attention": AttentionGatedParams(matt.mha), + } + + MSAColAttParams = lambda matt: { + "query_norm": LayerNormParams(matt._msa_att.layer_norm_m), + "attention": AttentionGatedParams(matt._msa_att.mha), + } + + MSAGlobalAttParams = lambda matt: { + "query_norm": LayerNormParams(matt.layer_norm_m), + "attention": GlobalAttentionParams(matt.global_attention), + } + + MSAAttPairBiasParams = lambda matt: dict( + **MSAAttParams(matt), + **{ + "feat_2d_norm": LayerNormParams(matt.layer_norm_z), + "feat_2d_weights": LinearWeight(matt.linear_z.weight), + }, + ) + + IPAParams = lambda ipa: { + "q_scalar": LinearParams(ipa.linear_q), + "kv_scalar": LinearParams(ipa.linear_kv), + "q_point_local": LinearParams(ipa.linear_q_points), + "kv_point_local": LinearParams(ipa.linear_kv_points), + "trainable_point_weights": Param( + param=ipa.head_weights, param_type=ParamType.Other + ), + "attention_2d": LinearParams(ipa.linear_b), + "output_projection": LinearParams(ipa.linear_out), + } + + TemplatePairBlockParams = lambda b: { + "triangle_attention_starting_node": TriAttParams(b.tri_att_start), + "triangle_attention_ending_node": TriAttParams(b.tri_att_end), + "triangle_multiplication_outgoing": TriMulOutParams(b.tri_mul_out), + "triangle_multiplication_incoming": TriMulInParams(b.tri_mul_in), + "pair_transition": PairTransitionParams(b.pair_transition), + } + + MSATransitionParams = lambda m: { + "input_layer_norm": LayerNormParams(m.layer_norm), + "transition1": LinearParams(m.linear_1), + "transition2": LinearParams(m.linear_2), + } + + OuterProductMeanParams = lambda o: { + "layer_norm_input": LayerNormParams(o.layer_norm), + "left_projection": LinearParams(o.linear_1), + "right_projection": LinearParams(o.linear_2), + "output_w": LinearWeightOPM(o.linear_out.weight), + "output_b": LinearBias(o.linear_out.bias), + } + + def EvoformerBlockParams(b, is_extra_msa=False): + if is_extra_msa: + col_att_name = "msa_column_global_attention" + msa_col_att_params = MSAGlobalAttParams(b.msa_att_col) + else: + col_att_name = "msa_column_attention" + msa_col_att_params = MSAColAttParams(b.msa_att_col) + + d = { + "msa_row_attention_with_pair_bias": MSAAttPairBiasParams( + b.msa_att_row + ), + col_att_name: msa_col_att_params, + "msa_transition": MSATransitionParams(b.core.msa_transition), + "outer_product_mean": + OuterProductMeanParams(b.core.outer_product_mean), + "triangle_multiplication_outgoing": + TriMulOutParams(b.core.tri_mul_out), + "triangle_multiplication_incoming": + TriMulInParams(b.core.tri_mul_in), + "triangle_attention_starting_node": + TriAttParams(b.core.tri_att_start), + "triangle_attention_ending_node": + TriAttParams(b.core.tri_att_end), + "pair_transition": + PairTransitionParams(b.core.pair_transition), + } + + return d + + ExtraMSABlockParams = partial(EvoformerBlockParams, is_extra_msa=True) + + FoldIterationParams = lambda sm: { + "invariant_point_attention": IPAParams(sm.ipa), + "attention_layer_norm": LayerNormParams(sm.layer_norm_ipa), + "transition": LinearParams(sm.transition.layers[0].linear_1), + "transition_1": LinearParams(sm.transition.layers[0].linear_2), + "transition_2": LinearParams(sm.transition.layers[0].linear_3), + "transition_layer_norm": LayerNormParams(sm.transition.layer_norm), + "affine_update": LinearParams(sm.bb_update.linear), + "rigid_sidechain": { + "input_projection": LinearParams(sm.angle_resnet.linear_in), + "input_projection_1": LinearParams(sm.angle_resnet.linear_initial), + "resblock1": LinearParams(sm.angle_resnet.layers[0].linear_1), + "resblock2": LinearParams(sm.angle_resnet.layers[0].linear_2), + "resblock1_1": LinearParams(sm.angle_resnet.layers[1].linear_1), + "resblock2_1": LinearParams(sm.angle_resnet.layers[1].linear_2), + "unnormalized_angles": LinearParams(sm.angle_resnet.linear_out), + }, + } + + ############################ + # translations dict overflow + ############################ + + tps_blocks = model.template_pair_stack.blocks + tps_blocks_params = stacked( + [TemplatePairBlockParams(b) for b in tps_blocks] + ) + + ems_blocks = model.extra_msa_stack.blocks + ems_blocks_params = stacked([ExtraMSABlockParams(b) for b in ems_blocks]) + + evo_blocks = model.evoformer.blocks + evo_blocks_params = stacked([EvoformerBlockParams(b) for b in evo_blocks]) + + translations = { + "evoformer": { + "preprocess_1d": LinearParams(model.input_embedder.linear_tf_m), + "preprocess_msa": LinearParams(model.input_embedder.linear_msa_m), + "left_single": LinearParams(model.input_embedder.linear_tf_z_i), + "right_single": LinearParams(model.input_embedder.linear_tf_z_j), + "prev_pos_linear": LinearParams(model.recycling_embedder.linear), + "prev_msa_first_row_norm": LayerNormParams( + model.recycling_embedder.layer_norm_m + ), + "prev_pair_norm": LayerNormParams( + model.recycling_embedder.layer_norm_z + ), + "pair_activiations": LinearParams( + model.input_embedder.linear_relpos + ), + "template_embedding": { + "single_template_embedding": { + "embedding2d": LinearParams( + model.template_pair_embedder.linear + ), + "template_pair_stack": { + "__layer_stack_no_state": tps_blocks_params, + }, + "output_layer_norm": LayerNormParams( + model.template_pair_stack.layer_norm + ), + }, + "attention": AttentionParams(model.template_pointwise_att.mha), + }, + "extra_msa_activations": LinearParams( + model.extra_msa_embedder.linear + ), + "extra_msa_stack": ems_blocks_params, + "template_single_embedding": LinearParams( + model.template_angle_embedder.linear_1 + ), + "template_projection": LinearParams( + model.template_angle_embedder.linear_2 + ), + "evoformer_iteration": evo_blocks_params, + "single_activations": LinearParams(model.evoformer.linear), + }, + "structure_module": { + "single_layer_norm": LayerNormParams( + model.structure_module.layer_norm_s + ), + "initial_projection": LinearParams( + model.structure_module.linear_in + ), + "pair_layer_norm": LayerNormParams( + model.structure_module.layer_norm_z + ), + "fold_iteration": FoldIterationParams(model.structure_module), + }, + "predicted_lddt_head": { + "input_layer_norm": LayerNormParams( + model.aux_heads.plddt.layer_norm + ), + "act_0": LinearParams(model.aux_heads.plddt.linear_1), + "act_1": LinearParams(model.aux_heads.plddt.linear_2), + "logits": LinearParams(model.aux_heads.plddt.linear_3), + }, + "distogram_head": { + "half_logits": LinearParams(model.aux_heads.distogram.linear), + }, + "experimentally_resolved_head": { + "logits": LinearParams( + model.aux_heads.experimentally_resolved.linear + ), + }, + "masked_msa_head": { + "logits": LinearParams(model.aux_heads.masked_msa.linear), + }, + } + + no_templ = [ + "model_3", + "model_4", + "model_5", + "model_3_ptm", + "model_4_ptm", + "model_5_ptm", + ] + if version in no_templ: + evo_dict = translations["evoformer"] + keys = list(evo_dict.keys()) + for k in keys: + if "template_" in k: + evo_dict.pop(k) + + if "_ptm" in version: + translations["predicted_aligned_error_head"] = { + "logits": LinearParams(model.aux_heads.tm.linear) + } + + # Flatten keys and insert missing key prefixes + flat = _process_translations_dict(translations) + + # Sanity check + keys = list(data.keys()) + flat_keys = list(flat.keys()) + incorrect = [k for k in flat_keys if k not in keys] + missing = [k for k in keys if k not in flat_keys] + # print(f"Incorrect: {incorrect}") + # print(f"Missing: {missing}") + + assert len(incorrect) == 0 + # assert(sorted(list(flat.keys())) == sorted(list(data.keys()))) + + # Set weights + assign(flat, data) diff --git a/gafl/openfold/utils/logger.py b/gafl/openfold/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e2223e3020765b8d847c269285a5f5de248b94 --- /dev/null +++ b/gafl/openfold/utils/logger.py @@ -0,0 +1,81 @@ +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import operator +import time + +import dllogger as logger +import numpy as np +import torch.cuda.profiler as profiler +from dllogger import JSONStreamBackend, StdOutBackend, Verbosity +from pytorch_lightning import Callback + + +def is_main_process(): + return int(os.getenv("LOCAL_RANK", "0")) == 0 + + +class PerformanceLoggingCallback(Callback): + def __init__(self, log_file, global_batch_size, warmup_steps: int = 0, profile: bool = False): + logger.init(backends=[JSONStreamBackend(Verbosity.VERBOSE, log_file), StdOutBackend(Verbosity.VERBOSE)]) + self.warmup_steps = warmup_steps + self.global_batch_size = global_batch_size + self.step = 0 + self.profile = profile + self.timestamps = [] + + def do_step(self): + self.step += 1 + if self.profile and self.step == self.warmup_steps: + profiler.start() + if self.step > self.warmup_steps: + self.timestamps.append(time.time()) + + def on_train_batch_start(self, trainer, pl_module, batch, batch_idx, dataloader_idx): + self.do_step() + + def on_test_batch_start(self, trainer, pl_module, batch, batch_idx, dataloader_idx): + self.do_step() + + def process_performance_stats(self, deltas): + def _round3(val): + return round(val, 3) + + throughput_imgps = _round3(self.global_batch_size / np.mean(deltas)) + timestamps_ms = 1000 * deltas + stats = { + f"throughput": throughput_imgps, + f"latency_mean": _round3(timestamps_ms.mean()), + } + for level in [90, 95, 99]: + stats.update({f"latency_{level}": _round3(np.percentile(timestamps_ms, level))}) + + return stats + + def _log(self): + if is_main_process(): + diffs = list(map(operator.sub, self.timestamps[1:], self.timestamps[:-1])) + deltas = np.array(diffs) + stats = self.process_performance_stats(deltas) + logger.log(step=(), data=stats) + logger.flush() + + def on_train_end(self, trainer, pl_module): + if self.profile: + profiler.stop() + self._log() + + def on_epoch_end(self, trainer, pl_module): + self._log() diff --git a/gafl/openfold/utils/loss.py b/gafl/openfold/utils/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..50809af9e7c3564e7104bfb298f50fc64f8dd597 --- /dev/null +++ b/gafl/openfold/utils/loss.py @@ -0,0 +1,1637 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +import logging +import ml_collections +import numpy as np +import torch +import torch.nn as nn +from torch.distributions.bernoulli import Bernoulli +from typing import Dict, Optional, Tuple + +from openfold.np import residue_constants +from openfold.utils import feats +from openfold.utils.rigid_utils import Rotation, Rigid +from openfold.utils.tensor_utils import ( + tree_map, + tensor_tree_map, + masked_mean, + permute_final_dims, + batched_gather, +) + + +def softmax_cross_entropy(logits, labels): + loss = -1 * torch.sum( + labels * torch.nn.functional.log_softmax(logits, dim=-1), + dim=-1, + ) + return loss + + +def sigmoid_cross_entropy(logits, labels): + log_p = torch.log(torch.sigmoid(logits)) + log_not_p = torch.log(torch.sigmoid(-logits)) + loss = -labels * log_p - (1 - labels) * log_not_p + return loss + + +def torsion_angle_loss( + a, # [*, N, 7, 2] + a_gt, # [*, N, 7, 2] + a_alt_gt, # [*, N, 7, 2] +): + # [*, N, 7] + norm = torch.norm(a, dim=-1) + + # [*, N, 7, 2] + a = a / norm.unsqueeze(-1) + + # [*, N, 7] + diff_norm_gt = torch.norm(a - a_gt, dim=-1) + diff_norm_alt_gt = torch.norm(a - a_alt_gt, dim=-1) + min_diff = torch.minimum(diff_norm_gt ** 2, diff_norm_alt_gt ** 2) + + # [*] + l_torsion = torch.mean(min_diff, dim=(-1, -2)) + l_angle_norm = torch.mean(torch.abs(norm - 1), dim=(-1, -2)) + + an_weight = 0.02 + return l_torsion + an_weight * l_angle_norm + + +def compute_fape( + pred_frames: Rigid, + target_frames: Rigid, + frames_mask: torch.Tensor, + pred_positions: torch.Tensor, + target_positions: torch.Tensor, + positions_mask: torch.Tensor, + length_scale: float, + l1_clamp_distance: Optional[float] = None, + eps=1e-8, + ignore_nan=True, +) -> torch.Tensor: + """ + Computes FAPE loss. + + Args: + pred_frames: + [*, N_frames] Rigid object of predicted frames + target_frames: + [*, N_frames] Rigid object of ground truth frames + frames_mask: + [*, N_frames] binary mask for the frames + pred_positions: + [*, N_pts, 3] predicted atom positions + target_positions: + [*, N_pts, 3] ground truth positions + positions_mask: + [*, N_pts] positions mask + length_scale: + Length scale by which the loss is divided + l1_clamp_distance: + Cutoff above which distance errors are disregarded + eps: + Small value used to regularize denominators + Returns: + [*] loss tensor + """ + # [*, N_frames, N_pts, 3] + local_pred_pos = pred_frames.invert()[..., None].apply( + pred_positions[..., None, :, :], + ) + local_target_pos = target_frames.invert()[..., None].apply( + target_positions[..., None, :, :], + ) + + error_dist = torch.sqrt( + torch.sum((local_pred_pos - local_target_pos) ** 2, dim=-1) + eps + ) + + if l1_clamp_distance is not None: + error_dist = torch.clamp(error_dist, min=0, max=l1_clamp_distance) + + normed_error = error_dist / length_scale + normed_error = normed_error * frames_mask[..., None] + normed_error = normed_error * positions_mask[..., None, :] + if ignore_nan: + normed_error = torch.nan_to_num(normed_error) + + # FP16-friendly averaging. Roughly equivalent to: + # + # norm_factor = ( + # torch.sum(frames_mask, dim=-1) * + # torch.sum(positions_mask, dim=-1) + # ) + # normed_error = torch.sum(normed_error, dim=(-1, -2)) / (eps + norm_factor) + # + # ("roughly" because eps is necessarily duplicated in the latter) + normed_error = torch.sum(normed_error, dim=-1) + normed_error = ( + normed_error / (eps + torch.sum(frames_mask, dim=-1))[..., None] + ) + normed_error = torch.sum(normed_error, dim=-1) + normed_error = normed_error / (eps + torch.sum(positions_mask, dim=-1)) + return normed_error + + +def backbone_loss( + backbone_rigid_tensor: torch.Tensor, + backbone_rigid_mask: torch.Tensor, + traj: torch.Tensor, + use_clamped_fape: Optional[torch.Tensor] = None, + clamp_distance: float = 10.0, + loss_unit_distance: float = 10.0, + eps: float = 1e-4, + **kwargs, +) -> torch.Tensor: + pred_aff = Rigid.from_tensor_7(traj) + pred_aff = Rigid( + Rotation(rot_mats=pred_aff.get_rots().get_rot_mats(), quats=None), + pred_aff.get_trans(), + ) + + # DISCREPANCY: DeepMind somehow gets a hold of a tensor_7 version of + # backbone tensor, normalizes it, and then turns it back to a rotation + # matrix. To avoid a potentially numerically unstable rotation matrix + # to quaternion conversion, we just use the original rotation matrix + # outright. This one hasn't been composed a bunch of times, though, so + # it might be fine. + gt_aff = Rigid.from_tensor_4x4(backbone_rigid_tensor) + + fape_loss = compute_fape( + pred_aff, + gt_aff[None], + backbone_rigid_mask[None], + pred_aff.get_trans(), + gt_aff[None].get_trans(), + backbone_rigid_mask[None], + l1_clamp_distance=clamp_distance, + length_scale=loss_unit_distance, + eps=eps, + ) + if use_clamped_fape is not None: + unclamped_fape_loss = compute_fape( + pred_aff, + gt_aff[None], + backbone_rigid_mask[None], + pred_aff.get_trans(), + gt_aff[None].get_trans(), + backbone_rigid_mask[None], + l1_clamp_distance=None, + length_scale=loss_unit_distance, + eps=eps, + ) + + fape_loss = fape_loss * use_clamped_fape + unclamped_fape_loss * ( + 1 - use_clamped_fape + ) + + # Average over the batch dimension + fape_loss = torch.mean(fape_loss) + + return fape_loss + + +def sidechain_loss( + sidechain_frames: torch.Tensor, + sidechain_atom_pos: torch.Tensor, + rigidgroups_gt_frames: torch.Tensor, + rigidgroups_alt_gt_frames: torch.Tensor, + rigidgroups_gt_exists: torch.Tensor, + renamed_atom14_gt_positions: torch.Tensor, + renamed_atom14_gt_exists: torch.Tensor, + alt_naming_is_better: torch.Tensor, + clamp_distance: float = 10.0, + length_scale: float = 10.0, + eps: float = 1e-4, + **kwargs, +) -> torch.Tensor: + renamed_gt_frames = ( + 1.0 - alt_naming_is_better[..., None, None, None] + ) * rigidgroups_gt_frames + alt_naming_is_better[ + ..., None, None, None + ] * rigidgroups_alt_gt_frames + + # Steamroll the inputs + sidechain_frames = sidechain_frames[-1] + batch_dims = sidechain_frames.shape[:-4] + sidechain_frames = sidechain_frames.view(*batch_dims, -1, 4, 4) + sidechain_frames = Rigid.from_tensor_4x4(sidechain_frames) + renamed_gt_frames = renamed_gt_frames.view(*batch_dims, -1, 4, 4) + renamed_gt_frames = Rigid.from_tensor_4x4(renamed_gt_frames) + rigidgroups_gt_exists = rigidgroups_gt_exists.reshape(*batch_dims, -1) + sidechain_atom_pos = sidechain_atom_pos[-1] + sidechain_atom_pos = sidechain_atom_pos.view(*batch_dims, -1, 3) + renamed_atom14_gt_positions = renamed_atom14_gt_positions.view( + *batch_dims, -1, 3 + ) + renamed_atom14_gt_exists = renamed_atom14_gt_exists.view(*batch_dims, -1) + + fape = compute_fape( + sidechain_frames, + renamed_gt_frames, + rigidgroups_gt_exists, + sidechain_atom_pos, + renamed_atom14_gt_positions, + renamed_atom14_gt_exists, + l1_clamp_distance=clamp_distance, + length_scale=length_scale, + eps=eps, + ) + + return fape + + +def fape_loss( + out: Dict[str, torch.Tensor], + batch: Dict[str, torch.Tensor], + config: ml_collections.ConfigDict, +) -> torch.Tensor: + bb_loss = backbone_loss( + traj=out["sm"]["frames"], + **{**batch, **config.backbone}, + ) + + sc_loss = sidechain_loss( + out["sm"]["sidechain_frames"], + out["sm"]["positions"], + **{**batch, **config.sidechain}, + ) + + loss = config.backbone.weight * bb_loss + config.sidechain.weight * sc_loss + + # Average over the batch dimension + loss = torch.mean(loss) + + return loss + + +def supervised_chi_loss( + angles_sin_cos: torch.Tensor, + unnormalized_angles_sin_cos: torch.Tensor, + aatype: torch.Tensor, + seq_mask: torch.Tensor, + chi_mask: torch.Tensor, + chi_angles_sin_cos: torch.Tensor, + chi_weight: float, + angle_norm_weight: float, + eps=1e-6, + **kwargs, +) -> torch.Tensor: + """ + Implements Algorithm 27 (torsionAngleLoss) + + Args: + angles_sin_cos: + [*, N, 7, 2] predicted angles + unnormalized_angles_sin_cos: + The same angles, but unnormalized + aatype: + [*, N] residue indices + seq_mask: + [*, N] sequence mask + chi_mask: + [*, N, 7] angle mask + chi_angles_sin_cos: + [*, N, 7, 2] ground truth angles + chi_weight: + Weight for the angle component of the loss + angle_norm_weight: + Weight for the normalization component of the loss + Returns: + [*] loss tensor + """ + pred_angles = angles_sin_cos[..., 3:, :] + residue_type_one_hot = torch.nn.functional.one_hot( + aatype, + residue_constants.restype_num + 1, + ) + chi_pi_periodic = torch.einsum( + "...ij,jk->ik", + residue_type_one_hot.type(angles_sin_cos.dtype), + angles_sin_cos.new_tensor(residue_constants.chi_pi_periodic), + ) + + true_chi = chi_angles_sin_cos[None] + + shifted_mask = (1 - 2 * chi_pi_periodic).unsqueeze(-1) + true_chi_shifted = shifted_mask * true_chi + sq_chi_error = torch.sum((true_chi - pred_angles) ** 2, dim=-1) + sq_chi_error_shifted = torch.sum( + (true_chi_shifted - pred_angles) ** 2, dim=-1 + ) + sq_chi_error = torch.minimum(sq_chi_error, sq_chi_error_shifted) + # The ol' switcheroo + sq_chi_error = sq_chi_error.permute( + *range(len(sq_chi_error.shape))[1:-2], 0, -2, -1 + ) + sq_chi_loss = masked_mean( + chi_mask[..., None, :, :], sq_chi_error, dim=(-1, -2, -3) + ) + + loss = chi_weight * sq_chi_loss + + angle_norm = torch.sqrt( + torch.sum(unnormalized_angles_sin_cos ** 2, dim=-1) + eps + ) + norm_error = torch.abs(angle_norm - 1.0) + norm_error = norm_error.permute( + *range(len(norm_error.shape))[1:-2], 0, -2, -1 + ) + angle_norm_loss = masked_mean( + seq_mask[..., None, :, None], norm_error, dim=(-1, -2, -3) + ) + + loss = loss + angle_norm_weight * angle_norm_loss + + # Average over the batch dimension + loss = torch.mean(loss) + + return loss + + +def compute_plddt(logits: torch.Tensor) -> torch.Tensor: + num_bins = logits.shape[-1] + bin_width = 1.0 / num_bins + bounds = torch.arange( + start=0.5 * bin_width, end=1.0, step=bin_width, device=logits.device + ) + probs = torch.nn.functional.softmax(logits, dim=-1) + pred_lddt_ca = torch.sum( + probs * bounds.view(*((1,) * len(probs.shape[:-1])), *bounds.shape), + dim=-1, + ) + return pred_lddt_ca * 100 + + +def lddt( + all_atom_pred_pos: torch.Tensor, + all_atom_positions: torch.Tensor, + all_atom_mask: torch.Tensor, + cutoff: float = 15.0, + eps: float = 1e-10, + per_residue: bool = True, +) -> torch.Tensor: + n = all_atom_mask.shape[-2] + dmat_true = torch.sqrt( + eps + + torch.sum( + ( + all_atom_positions[..., None, :] + - all_atom_positions[..., None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + dmat_pred = torch.sqrt( + eps + + torch.sum( + ( + all_atom_pred_pos[..., None, :] + - all_atom_pred_pos[..., None, :, :] + ) + ** 2, + dim=-1, + ) + ) + dists_to_score = ( + (dmat_true < cutoff) + * all_atom_mask + * permute_final_dims(all_atom_mask, (1, 0)) + * (1.0 - torch.eye(n, device=all_atom_mask.device)) + ) + + dist_l1 = torch.abs(dmat_true - dmat_pred) + + score = ( + (dist_l1 < 0.5).type(dist_l1.dtype) + + (dist_l1 < 1.0).type(dist_l1.dtype) + + (dist_l1 < 2.0).type(dist_l1.dtype) + + (dist_l1 < 4.0).type(dist_l1.dtype) + ) + score = score * 0.25 + + dims = (-1,) if per_residue else (-2, -1) + norm = 1.0 / (eps + torch.sum(dists_to_score, dim=dims)) + score = norm * (eps + torch.sum(dists_to_score * score, dim=dims)) + + return score + + +def lddt_ca( + all_atom_pred_pos: torch.Tensor, + all_atom_positions: torch.Tensor, + all_atom_mask: torch.Tensor, + cutoff: float = 15.0, + eps: float = 1e-10, + per_residue: bool = True, +) -> torch.Tensor: + ca_pos = residue_constants.atom_order["CA"] + all_atom_pred_pos = all_atom_pred_pos[..., ca_pos, :] + all_atom_positions = all_atom_positions[..., ca_pos, :] + all_atom_mask = all_atom_mask[..., ca_pos : (ca_pos + 1)] # keep dim + + return lddt( + all_atom_pred_pos, + all_atom_positions, + all_atom_mask, + cutoff=cutoff, + eps=eps, + per_residue=per_residue, + ) + + +def lddt_loss( + logits: torch.Tensor, + all_atom_pred_pos: torch.Tensor, + all_atom_positions: torch.Tensor, + all_atom_mask: torch.Tensor, + resolution: torch.Tensor, + cutoff: float = 15.0, + no_bins: int = 50, + min_resolution: float = 0.1, + max_resolution: float = 3.0, + eps: float = 1e-10, + **kwargs, +) -> torch.Tensor: + n = all_atom_mask.shape[-2] + + ca_pos = residue_constants.atom_order["CA"] + all_atom_pred_pos = all_atom_pred_pos[..., ca_pos, :] + all_atom_positions = all_atom_positions[..., ca_pos, :] + all_atom_mask = all_atom_mask[..., ca_pos : (ca_pos + 1)] # keep dim + + score = lddt( + all_atom_pred_pos, + all_atom_positions, + all_atom_mask, + cutoff=cutoff, + eps=eps + ) + + score = score.detach() + + bin_index = torch.floor(score * no_bins).long() + bin_index = torch.clamp(bin_index, max=(no_bins - 1)) + lddt_ca_one_hot = torch.nn.functional.one_hot( + bin_index, num_classes=no_bins + ) + + errors = softmax_cross_entropy(logits, lddt_ca_one_hot) + all_atom_mask = all_atom_mask.squeeze(-1) + loss = torch.sum(errors * all_atom_mask, dim=-1) / ( + eps + torch.sum(all_atom_mask, dim=-1) + ) + + loss = loss * ( + (resolution >= min_resolution) & (resolution <= max_resolution) + ) + + # Average over the batch dimension + loss = torch.mean(loss) + + return loss + + +def distogram_loss( + logits, + pseudo_beta, + pseudo_beta_mask, + min_bin=2.3125, + max_bin=21.6875, + no_bins=64, + eps=1e-6, + **kwargs, +): + boundaries = torch.linspace( + min_bin, + max_bin, + no_bins - 1, + device=logits.device, + ) + boundaries = boundaries ** 2 + + dists = torch.sum( + (pseudo_beta[..., None, :] - pseudo_beta[..., None, :, :]) ** 2, + dim=-1, + keepdims=True, + ) + + true_bins = torch.sum(dists > boundaries, dim=-1) + + errors = softmax_cross_entropy( + logits, + torch.nn.functional.one_hot(true_bins, no_bins), + ) + + square_mask = pseudo_beta_mask[..., None] * pseudo_beta_mask[..., None, :] + + # FP16-friendly sum. Equivalent to: + # mean = (torch.sum(errors * square_mask, dim=(-1, -2)) / + # (eps + torch.sum(square_mask, dim=(-1, -2)))) + denom = eps + torch.sum(square_mask, dim=(-1, -2)) + mean = errors * square_mask + mean = torch.sum(mean, dim=-1) + mean = mean / denom[..., None] + mean = torch.sum(mean, dim=-1) + + # Average over the batch dimensions + mean = torch.mean(mean) + + return mean + + +def _calculate_bin_centers(boundaries: torch.Tensor): + step = boundaries[1] - boundaries[0] + bin_centers = boundaries + step / 2 + bin_centers = torch.cat( + [bin_centers, (bin_centers[-1] + step).unsqueeze(-1)], dim=0 + ) + return bin_centers + + +def _calculate_expected_aligned_error( + alignment_confidence_breaks: torch.Tensor, + aligned_distance_error_probs: torch.Tensor, +) -> Tuple[torch.Tensor, torch.Tensor]: + bin_centers = _calculate_bin_centers(alignment_confidence_breaks) + return ( + torch.sum(aligned_distance_error_probs * bin_centers, dim=-1), + bin_centers[-1], + ) + + +def compute_predicted_aligned_error( + logits: torch.Tensor, + max_bin: int = 31, + no_bins: int = 64, + **kwargs, +) -> Dict[str, torch.Tensor]: + """Computes aligned confidence metrics from logits. + + Args: + logits: [*, num_res, num_res, num_bins] the logits output from + PredictedAlignedErrorHead. + max_bin: Maximum bin value + no_bins: Number of bins + Returns: + aligned_confidence_probs: [*, num_res, num_res, num_bins] the predicted + aligned error probabilities over bins for each residue pair. + predicted_aligned_error: [*, num_res, num_res] the expected aligned distance + error for each pair of residues. + max_predicted_aligned_error: [*] the maximum predicted error possible. + """ + boundaries = torch.linspace( + 0, max_bin, steps=(no_bins - 1), device=logits.device + ) + + aligned_confidence_probs = torch.nn.functional.softmax(logits, dim=-1) + ( + predicted_aligned_error, + max_predicted_aligned_error, + ) = _calculate_expected_aligned_error( + alignment_confidence_breaks=boundaries, + aligned_distance_error_probs=aligned_confidence_probs, + ) + + return { + "aligned_confidence_probs": aligned_confidence_probs, + "predicted_aligned_error": predicted_aligned_error, + "max_predicted_aligned_error": max_predicted_aligned_error, + } + + +def compute_tm( + logits: torch.Tensor, + residue_weights: Optional[torch.Tensor] = None, + max_bin: int = 31, + no_bins: int = 64, + eps: float = 1e-8, + **kwargs, +) -> torch.Tensor: + if residue_weights is None: + residue_weights = logits.new_ones(logits.shape[-2]) + + boundaries = torch.linspace( + 0, max_bin, steps=(no_bins - 1), device=logits.device + ) + + bin_centers = _calculate_bin_centers(boundaries) + torch.sum(residue_weights) + n = logits.shape[-2] + clipped_n = max(n, 19) + + d0 = 1.24 * (clipped_n - 15) ** (1.0 / 3) - 1.8 + + probs = torch.nn.functional.softmax(logits, dim=-1) + + tm_per_bin = 1.0 / (1 + (bin_centers ** 2) / (d0 ** 2)) + predicted_tm_term = torch.sum(probs * tm_per_bin, dim=-1) + + normed_residue_mask = residue_weights / (eps + residue_weights.sum()) + per_alignment = torch.sum(predicted_tm_term * normed_residue_mask, dim=-1) + weighted = per_alignment * residue_weights + argmax = (weighted == torch.max(weighted)).nonzero()[0] + return per_alignment[tuple(argmax)] + + +def tm_loss( + logits, + final_affine_tensor, + backbone_rigid_tensor, + backbone_rigid_mask, + resolution, + max_bin=31, + no_bins=64, + min_resolution: float = 0.1, + max_resolution: float = 3.0, + eps=1e-8, + **kwargs, +): + pred_affine = Rigid.from_tensor_7(final_affine_tensor) + backbone_rigid = Rigid.from_tensor_4x4(backbone_rigid_tensor) + + def _points(affine): + pts = affine.get_trans()[..., None, :, :] + return affine.invert()[..., None].apply(pts) + + sq_diff = torch.sum( + (_points(pred_affine) - _points(backbone_rigid)) ** 2, dim=-1 + ) + + sq_diff = sq_diff.detach() + + boundaries = torch.linspace( + 0, max_bin, steps=(no_bins - 1), device=logits.device + ) + boundaries = boundaries ** 2 + true_bins = torch.sum(sq_diff[..., None] > boundaries, dim=-1) + + errors = softmax_cross_entropy( + logits, torch.nn.functional.one_hot(true_bins, no_bins) + ) + + square_mask = ( + backbone_rigid_mask[..., None] * backbone_rigid_mask[..., None, :] + ) + + loss = torch.sum(errors * square_mask, dim=-1) + scale = 0.5 # hack to help FP16 training along + denom = eps + torch.sum(scale * square_mask, dim=(-1, -2)) + loss = loss / denom[..., None] + loss = torch.sum(loss, dim=-1) + loss = loss * scale + + loss = loss * ( + (resolution >= min_resolution) & (resolution <= max_resolution) + ) + + # Average over the loss dimension + loss = torch.mean(loss) + + return loss + + +def between_residue_bond_loss( + pred_atom_positions: torch.Tensor, # (*, N, 37/14, 3) + pred_atom_mask: torch.Tensor, # (*, N, 37/14) + residue_index: torch.Tensor, # (*, N) + aatype: torch.Tensor, # (*, N) + tolerance_factor_soft=12.0, + tolerance_factor_hard=12.0, + eps=1e-6, +) -> Dict[str, torch.Tensor]: + """Flat-bottom loss to penalize structural violations between residues. + + This is a loss penalizing any violation of the geometry around the peptide + bond between consecutive amino acids. This loss corresponds to + Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 44, 45. + + Args: + pred_atom_positions: Atom positions in atom37/14 representation + pred_atom_mask: Atom mask in atom37/14 representation + residue_index: Residue index for given amino acid, this is assumed to be + monotonically increasing. + aatype: Amino acid type of given residue + tolerance_factor_soft: soft tolerance factor measured in standard deviations + of pdb distributions + tolerance_factor_hard: hard tolerance factor measured in standard deviations + of pdb distributions + + Returns: + Dict containing: + * 'c_n_loss_mean': Loss for peptide bond length violations + * 'ca_c_n_loss_mean': Loss for violations of bond angle around C spanned + by CA, C, N + * 'c_n_ca_loss_mean': Loss for violations of bond angle around N spanned + by C, N, CA + * 'per_residue_loss_sum': sum of all losses for each residue + * 'per_residue_violation_mask': mask denoting all residues with violation + present. + """ + # Get the positions of the relevant backbone atoms. + this_ca_pos = pred_atom_positions[..., :-1, 1, :] + this_ca_mask = pred_atom_mask[..., :-1, 1] + this_c_pos = pred_atom_positions[..., :-1, 2, :] + this_c_mask = pred_atom_mask[..., :-1, 2] + next_n_pos = pred_atom_positions[..., 1:, 0, :] + next_n_mask = pred_atom_mask[..., 1:, 0] + next_ca_pos = pred_atom_positions[..., 1:, 1, :] + next_ca_mask = pred_atom_mask[..., 1:, 1] + has_no_gap_mask = (residue_index[..., 1:] - residue_index[..., :-1]) == 1.0 + + # Compute loss for the C--N bond. + c_n_bond_length = torch.sqrt( + eps + torch.sum((this_c_pos - next_n_pos) ** 2, dim=-1) + ) + + # The C-N bond to proline has slightly different length because of the ring. + next_is_proline = aatype[..., 1:] == residue_constants.resname_to_idx["PRO"] + gt_length = ( + ~next_is_proline + ) * residue_constants.between_res_bond_length_c_n[ + 0 + ] + next_is_proline * residue_constants.between_res_bond_length_c_n[ + 1 + ] + gt_stddev = ( + ~next_is_proline + ) * residue_constants.between_res_bond_length_stddev_c_n[ + 0 + ] + next_is_proline * residue_constants.between_res_bond_length_stddev_c_n[ + 1 + ] + c_n_bond_length_error = torch.sqrt(eps + (c_n_bond_length - gt_length) ** 2) + c_n_loss_per_residue = torch.nn.functional.relu( + c_n_bond_length_error - tolerance_factor_soft * gt_stddev + ) + mask = this_c_mask * next_n_mask * has_no_gap_mask + c_n_loss = torch.sum(mask * c_n_loss_per_residue, dim=-1) / ( + torch.sum(mask, dim=-1) + eps + ) + c_n_violation_mask = mask * ( + c_n_bond_length_error > (tolerance_factor_hard * gt_stddev) + ) + + # Compute loss for the angles. + ca_c_bond_length = torch.sqrt( + eps + torch.sum((this_ca_pos - this_c_pos) ** 2, dim=-1) + ) + n_ca_bond_length = torch.sqrt( + eps + torch.sum((next_n_pos - next_ca_pos) ** 2, dim=-1) + ) + + c_ca_unit_vec = (this_ca_pos - this_c_pos) / ca_c_bond_length[..., None] + c_n_unit_vec = (next_n_pos - this_c_pos) / c_n_bond_length[..., None] + n_ca_unit_vec = (next_ca_pos - next_n_pos) / n_ca_bond_length[..., None] + + ca_c_n_cos_angle = torch.sum(c_ca_unit_vec * c_n_unit_vec, dim=-1) + gt_angle = residue_constants.between_res_cos_angles_ca_c_n[0] + gt_stddev = residue_constants.between_res_bond_length_stddev_c_n[0] + ca_c_n_cos_angle_error = torch.sqrt( + eps + (ca_c_n_cos_angle - gt_angle) ** 2 + ) + ca_c_n_loss_per_residue = torch.nn.functional.relu( + ca_c_n_cos_angle_error - tolerance_factor_soft * gt_stddev + ) + mask = this_ca_mask * this_c_mask * next_n_mask * has_no_gap_mask + ca_c_n_loss = torch.sum(mask * ca_c_n_loss_per_residue, dim=-1) / ( + torch.sum(mask, dim=-1) + eps + ) + ca_c_n_violation_mask = mask * ( + ca_c_n_cos_angle_error > (tolerance_factor_hard * gt_stddev) + ) + + c_n_ca_cos_angle = torch.sum((-c_n_unit_vec) * n_ca_unit_vec, dim=-1) + gt_angle = residue_constants.between_res_cos_angles_c_n_ca[0] + gt_stddev = residue_constants.between_res_cos_angles_c_n_ca[1] + c_n_ca_cos_angle_error = torch.sqrt( + eps + torch.square(c_n_ca_cos_angle - gt_angle) + ) + c_n_ca_loss_per_residue = torch.nn.functional.relu( + c_n_ca_cos_angle_error - tolerance_factor_soft * gt_stddev + ) + mask = this_c_mask * next_n_mask * next_ca_mask * has_no_gap_mask + c_n_ca_loss = torch.sum(mask * c_n_ca_loss_per_residue, dim=-1) / ( + torch.sum(mask, dim=-1) + eps + ) + c_n_ca_violation_mask = mask * ( + c_n_ca_cos_angle_error > (tolerance_factor_hard * gt_stddev) + ) + + # Compute a per residue loss (equally distribute the loss to both + # neighbouring residues). + per_residue_loss_sum = ( + c_n_loss_per_residue + ca_c_n_loss_per_residue + c_n_ca_loss_per_residue + ) + per_residue_loss_sum = 0.5 * ( + torch.nn.functional.pad(per_residue_loss_sum, (0, 1)) + + torch.nn.functional.pad(per_residue_loss_sum, (1, 0)) + ) + + # Compute hard violations. + violation_mask = torch.max( + torch.stack( + [c_n_violation_mask, ca_c_n_violation_mask, c_n_ca_violation_mask], + dim=-2, + ), + dim=-2, + )[0] + violation_mask = torch.maximum( + torch.nn.functional.pad(violation_mask, (0, 1)), + torch.nn.functional.pad(violation_mask, (1, 0)), + ) + + return { + "c_n_loss_mean": c_n_loss, + "ca_c_n_loss_mean": ca_c_n_loss, + "c_n_ca_loss_mean": c_n_ca_loss, + "per_residue_loss_sum": per_residue_loss_sum, + "per_residue_violation_mask": violation_mask, + } + + +def between_residue_clash_loss( + atom14_pred_positions: torch.Tensor, + atom14_atom_exists: torch.Tensor, + atom14_atom_radius: torch.Tensor, + residue_index: torch.Tensor, + overlap_tolerance_soft=1.5, + overlap_tolerance_hard=1.5, + eps=1e-10, +) -> Dict[str, torch.Tensor]: + """Loss to penalize steric clashes between residues. + + This is a loss penalizing any steric clashes due to non bonded atoms in + different peptides coming too close. This loss corresponds to the part with + different residues of + Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 46. + + Args: + atom14_pred_positions: Predicted positions of atoms in + global prediction frame + atom14_atom_exists: Mask denoting whether atom at positions exists for given + amino acid type + atom14_atom_radius: Van der Waals radius for each atom. + residue_index: Residue index for given amino acid. + overlap_tolerance_soft: Soft tolerance factor. + overlap_tolerance_hard: Hard tolerance factor. + + Returns: + Dict containing: + * 'mean_loss': average clash loss + * 'per_atom_loss_sum': sum of all clash losses per atom, shape (N, 14) + * 'per_atom_clash_mask': mask whether atom clashes with any other atom + shape (N, 14) + """ + fp_type = atom14_pred_positions.dtype + + # Create the distance matrix. + # (N, N, 14, 14) + dists = torch.sqrt( + eps + + torch.sum( + ( + atom14_pred_positions[..., :, None, :, None, :] + - atom14_pred_positions[..., None, :, None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + # Create the mask for valid distances. + # shape (N, N, 14, 14) + dists_mask = ( + atom14_atom_exists[..., :, None, :, None] + * atom14_atom_exists[..., None, :, None, :] + ).type(fp_type) + + # Mask out all the duplicate entries in the lower triangular matrix. + # Also mask out the diagonal (atom-pairs from the same residue) -- these atoms + # are handled separately. + dists_mask = dists_mask * ( + residue_index[..., :, None, None, None] + < residue_index[..., None, :, None, None] + ) + + # Backbone C--N bond between subsequent residues is no clash. + c_one_hot = torch.nn.functional.one_hot( + residue_index.new_tensor(2), num_classes=14 + ) + c_one_hot = c_one_hot.reshape( + *((1,) * len(residue_index.shape[:-1])), *c_one_hot.shape + ) + c_one_hot = c_one_hot.type(fp_type) + n_one_hot = torch.nn.functional.one_hot( + residue_index.new_tensor(0), num_classes=14 + ) + n_one_hot = n_one_hot.reshape( + *((1,) * len(residue_index.shape[:-1])), *n_one_hot.shape + ) + n_one_hot = n_one_hot.type(fp_type) + + neighbour_mask = ( + residue_index[..., :, None, None, None] + 1 + ) == residue_index[..., None, :, None, None] + c_n_bonds = ( + neighbour_mask + * c_one_hot[..., None, None, :, None] + * n_one_hot[..., None, None, None, :] + ) + dists_mask = dists_mask * (1.0 - c_n_bonds) + + # Disulfide bridge between two cysteines is no clash. + cys = residue_constants.restype_name_to_atom14_names["CYS"] + cys_sg_idx = cys.index("SG") + cys_sg_idx = residue_index.new_tensor(cys_sg_idx) + cys_sg_idx = cys_sg_idx.reshape( + *((1,) * len(residue_index.shape[:-1])), 1 + ).squeeze(-1) + cys_sg_one_hot = torch.nn.functional.one_hot(cys_sg_idx, num_classes=14) + disulfide_bonds = ( + cys_sg_one_hot[..., None, None, :, None] + * cys_sg_one_hot[..., None, None, None, :] + ) + dists_mask = dists_mask * (1.0 - disulfide_bonds) + + # Compute the lower bound for the allowed distances. + # shape (N, N, 14, 14) + dists_lower_bound = dists_mask * ( + atom14_atom_radius[..., :, None, :, None] + + atom14_atom_radius[..., None, :, None, :] + ) + + # Compute the error. + # shape (N, N, 14, 14) + dists_to_low_error = dists_mask * torch.nn.functional.relu( + dists_lower_bound - overlap_tolerance_soft - dists + ) + + # Compute the mean loss. + # shape () + mean_loss = torch.sum(dists_to_low_error) / (1e-6 + torch.sum(dists_mask)) + + # Compute the per atom loss sum. + # shape (N, 14) + per_atom_loss_sum = torch.sum(dists_to_low_error, dim=(-4, -2)) + torch.sum( + dists_to_low_error, axis=(-3, -1) + ) + + # Compute the hard clash mask. + # shape (N, N, 14, 14) + clash_mask = dists_mask * ( + dists < (dists_lower_bound - overlap_tolerance_hard) + ) + + # Compute the per atom clash. + # shape (N, 14) + per_atom_clash_mask = torch.maximum( + torch.amax(clash_mask, axis=(-4, -2)), + torch.amax(clash_mask, axis=(-3, -1)), + ) + + return { + "mean_loss": mean_loss, # shape () + "per_atom_loss_sum": per_atom_loss_sum, # shape (N, 14) + "per_atom_clash_mask": per_atom_clash_mask, # shape (N, 14) + } + + +def within_residue_violations( + atom14_pred_positions: torch.Tensor, + atom14_atom_exists: torch.Tensor, + atom14_dists_lower_bound: torch.Tensor, + atom14_dists_upper_bound: torch.Tensor, + tighten_bounds_for_loss=0.0, + eps=1e-10, +) -> Dict[str, torch.Tensor]: + """Loss to penalize steric clashes within residues. + + This is a loss penalizing any steric violations or clashes of non-bonded atoms + in a given peptide. This loss corresponds to the part with + the same residues of + Jumper et al. (2021) Suppl. Sec. 1.9.11, eq 46. + + Args: + atom14_pred_positions ([*, N, 14, 3]): + Predicted positions of atoms in global prediction frame. + atom14_atom_exists ([*, N, 14]): + Mask denoting whether atom at positions exists for given + amino acid type + atom14_dists_lower_bound ([*, N, 14]): + Lower bound on allowed distances. + atom14_dists_upper_bound ([*, N, 14]): + Upper bound on allowed distances + tighten_bounds_for_loss ([*, N]): + Extra factor to tighten loss + + Returns: + Dict containing: + * 'per_atom_loss_sum' ([*, N, 14]): + sum of all clash losses per atom, shape + * 'per_atom_clash_mask' ([*, N, 14]): + mask whether atom clashes with any other atom shape + """ + # Compute the mask for each residue. + dists_masks = 1.0 - torch.eye(14, device=atom14_atom_exists.device)[None] + dists_masks = dists_masks.reshape( + *((1,) * len(atom14_atom_exists.shape[:-2])), *dists_masks.shape + ) + dists_masks = ( + atom14_atom_exists[..., :, :, None] + * atom14_atom_exists[..., :, None, :] + * dists_masks + ) + + # Distance matrix + dists = torch.sqrt( + eps + + torch.sum( + ( + atom14_pred_positions[..., :, :, None, :] + - atom14_pred_positions[..., :, None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + # Compute the loss. + dists_to_low_error = torch.nn.functional.relu( + atom14_dists_lower_bound + tighten_bounds_for_loss - dists + ) + dists_to_high_error = torch.nn.functional.relu( + dists - (atom14_dists_upper_bound - tighten_bounds_for_loss) + ) + loss = dists_masks * (dists_to_low_error + dists_to_high_error) + + # Compute the per atom loss sum. + per_atom_loss_sum = torch.sum(loss, dim=-2) + torch.sum(loss, dim=-1) + + # Compute the violations mask. + violations = dists_masks * ( + (dists < atom14_dists_lower_bound) | (dists > atom14_dists_upper_bound) + ) + + # Compute the per atom violations. + per_atom_violations = torch.maximum( + torch.max(violations, dim=-2)[0], torch.max(violations, axis=-1)[0] + ) + + return { + "per_atom_loss_sum": per_atom_loss_sum, + "per_atom_violations": per_atom_violations, + } + + +def find_structural_violations( + batch: Dict[str, torch.Tensor], + atom14_pred_positions: torch.Tensor, + violation_tolerance_factor: float, + clash_overlap_tolerance: float, + **kwargs, +) -> Dict[str, torch.Tensor]: + """Computes several checks for structural violations.""" + + # Compute between residue backbone violations of bonds and angles. + connection_violations = between_residue_bond_loss( + pred_atom_positions=atom14_pred_positions, + pred_atom_mask=batch["atom14_atom_exists"], + residue_index=batch["residue_index"], + aatype=batch["aatype"], + tolerance_factor_soft=violation_tolerance_factor, + tolerance_factor_hard=violation_tolerance_factor, + ) + + # Compute the Van der Waals radius for every atom + # (the first letter of the atom name is the element type). + # Shape: (N, 14). + atomtype_radius = [ + residue_constants.van_der_waals_radius[name[0]] + for name in residue_constants.atom_types + ] + atomtype_radius = atom14_pred_positions.new_tensor(atomtype_radius) + atom14_atom_radius = ( + batch["atom14_atom_exists"] + * atomtype_radius[batch["residx_atom14_to_atom37"]] + ) + + # Compute the between residue clash loss. + between_residue_clashes = between_residue_clash_loss( + atom14_pred_positions=atom14_pred_positions, + atom14_atom_exists=batch["atom14_atom_exists"], + atom14_atom_radius=atom14_atom_radius, + residue_index=batch["residue_index"], + overlap_tolerance_soft=clash_overlap_tolerance, + overlap_tolerance_hard=clash_overlap_tolerance, + ) + + # Compute all within-residue violations (clashes, + # bond length and angle violations). + restype_atom14_bounds = residue_constants.make_atom14_dists_bounds( + overlap_tolerance=clash_overlap_tolerance, + bond_length_tolerance_factor=violation_tolerance_factor, + ) + atom14_atom_exists = batch["atom14_atom_exists"] + atom14_dists_lower_bound = atom14_pred_positions.new_tensor( + restype_atom14_bounds["lower_bound"] + )[batch["aatype"]] + atom14_dists_upper_bound = atom14_pred_positions.new_tensor( + restype_atom14_bounds["upper_bound"] + )[batch["aatype"]] + residue_violations = within_residue_violations( + atom14_pred_positions=atom14_pred_positions, + atom14_atom_exists=batch["atom14_atom_exists"], + atom14_dists_lower_bound=atom14_dists_lower_bound, + atom14_dists_upper_bound=atom14_dists_upper_bound, + tighten_bounds_for_loss=0.0, + ) + + # Combine them to a single per-residue violation mask (used later for LDDT). + per_residue_violations_mask = torch.max( + torch.stack( + [ + connection_violations["per_residue_violation_mask"], + torch.max( + between_residue_clashes["per_atom_clash_mask"], dim=-1 + )[0], + torch.max(residue_violations["per_atom_violations"], dim=-1)[0], + ], + dim=-1, + ), + dim=-1, + )[0] + + return { + "between_residues": { + "bonds_c_n_loss_mean": connection_violations["c_n_loss_mean"], # () + "angles_ca_c_n_loss_mean": connection_violations[ + "ca_c_n_loss_mean" + ], # () + "angles_c_n_ca_loss_mean": connection_violations[ + "c_n_ca_loss_mean" + ], # () + "connections_per_residue_loss_sum": connection_violations[ + "per_residue_loss_sum" + ], # (N) + "connections_per_residue_violation_mask": connection_violations[ + "per_residue_violation_mask" + ], # (N) + "clashes_mean_loss": between_residue_clashes["mean_loss"], # () + "clashes_per_atom_loss_sum": between_residue_clashes[ + "per_atom_loss_sum" + ], # (N, 14) + "clashes_per_atom_clash_mask": between_residue_clashes[ + "per_atom_clash_mask" + ], # (N, 14) + }, + "within_residues": { + "per_atom_loss_sum": residue_violations[ + "per_atom_loss_sum" + ], # (N, 14) + "per_atom_violations": residue_violations[ + "per_atom_violations" + ], # (N, 14), + }, + "total_per_residue_violations_mask": per_residue_violations_mask, # (N) + } + + +def find_structural_violations_np( + batch: Dict[str, np.ndarray], + atom14_pred_positions: np.ndarray, + config: ml_collections.ConfigDict, +) -> Dict[str, np.ndarray]: + to_tensor = lambda x: torch.tensor(x) + batch = tree_map(to_tensor, batch, np.ndarray) + atom14_pred_positions = to_tensor(atom14_pred_positions) + + out = find_structural_violations(batch, atom14_pred_positions, **config) + + to_np = lambda x: np.array(x) + np_out = tensor_tree_map(to_np, out) + + return np_out + + +def extreme_ca_ca_distance_violations( + pred_atom_positions: torch.Tensor, # (N, 37(14), 3) + pred_atom_mask: torch.Tensor, # (N, 37(14)) + residue_index: torch.Tensor, # (N) + max_angstrom_tolerance=1.5, + eps=1e-6, +) -> torch.Tensor: + """Counts residues whose Ca is a large distance from its neighbour. + + Measures the fraction of CA-CA pairs between consecutive amino acids that are + more than 'max_angstrom_tolerance' apart. + + Args: + pred_atom_positions: Atom positions in atom37/14 representation + pred_atom_mask: Atom mask in atom37/14 representation + residue_index: Residue index for given amino acid, this is assumed to be + monotonically increasing. + max_angstrom_tolerance: Maximum distance allowed to not count as violation. + Returns: + Fraction of consecutive CA-CA pairs with violation. + """ + this_ca_pos = pred_atom_positions[..., :-1, 1, :] + this_ca_mask = pred_atom_mask[..., :-1, 1] + next_ca_pos = pred_atom_positions[..., 1:, 1, :] + next_ca_mask = pred_atom_mask[..., 1:, 1] + has_no_gap_mask = (residue_index[..., 1:] - residue_index[..., :-1]) == 1.0 + ca_ca_distance = torch.sqrt( + eps + torch.sum((this_ca_pos - next_ca_pos) ** 2, dim=-1) + ) + violations = ( + ca_ca_distance - residue_constants.ca_ca + ) > max_angstrom_tolerance + mask = this_ca_mask * next_ca_mask * has_no_gap_mask + mean = masked_mean(mask, violations, -1) + return mean + + +def compute_violation_metrics( + batch: Dict[str, torch.Tensor], + atom14_pred_positions: torch.Tensor, # (N, 14, 3) + violations: Dict[str, torch.Tensor], +) -> Dict[str, torch.Tensor]: + """Compute several metrics to assess the structural violations.""" + ret = {} + extreme_ca_ca_violations = extreme_ca_ca_distance_violations( + pred_atom_positions=atom14_pred_positions, + pred_atom_mask=batch["atom14_atom_exists"], + residue_index=batch["residue_index"], + ) + ret["violations_extreme_ca_ca_distance"] = extreme_ca_ca_violations + ret["violations_between_residue_bond"] = masked_mean( + batch["seq_mask"], + violations["between_residues"][ + "connections_per_residue_violation_mask" + ], + dim=-1, + ) + ret["violations_between_residue_clash"] = masked_mean( + mask=batch["seq_mask"], + value=torch.max( + violations["between_residues"]["clashes_per_atom_clash_mask"], + dim=-1, + )[0], + dim=-1, + ) + ret["violations_within_residue"] = masked_mean( + mask=batch["seq_mask"], + value=torch.max( + violations["within_residues"]["per_atom_violations"], dim=-1 + )[0], + dim=-1, + ) + ret["violations_per_residue"] = masked_mean( + mask=batch["seq_mask"], + value=violations["total_per_residue_violations_mask"], + dim=-1, + ) + return ret + + +def compute_violation_metrics_np( + batch: Dict[str, np.ndarray], + atom14_pred_positions: np.ndarray, + violations: Dict[str, np.ndarray], +) -> Dict[str, np.ndarray]: + to_tensor = lambda x: torch.tensor(x) + batch = tree_map(to_tensor, batch, np.ndarray) + atom14_pred_positions = to_tensor(atom14_pred_positions) + violations = tree_map(to_tensor, violations, np.ndarray) + + out = compute_violation_metrics(batch, atom14_pred_positions, violations) + + to_np = lambda x: np.array(x) + return tree_map(to_np, out, torch.Tensor) + + +def violation_loss( + violations: Dict[str, torch.Tensor], + atom14_atom_exists: torch.Tensor, + eps=1e-6, + **kwargs, +) -> torch.Tensor: + num_atoms = torch.sum(atom14_atom_exists) + l_clash = torch.sum( + violations["between_residues"]["clashes_per_atom_loss_sum"] + + violations["within_residues"]["per_atom_loss_sum"] + ) + l_clash = l_clash / (eps + num_atoms) + loss = ( + violations["between_residues"]["bonds_c_n_loss_mean"] + + violations["between_residues"]["angles_ca_c_n_loss_mean"] + + violations["between_residues"]["angles_c_n_ca_loss_mean"] + + l_clash + ) + + return loss + + +def compute_renamed_ground_truth( + batch: Dict[str, torch.Tensor], + atom14_pred_positions: torch.Tensor, + eps=1e-10, +) -> Dict[str, torch.Tensor]: + """ + Find optimal renaming of ground truth based on the predicted positions. + + Alg. 26 "renameSymmetricGroundTruthAtoms" + + This renamed ground truth is then used for all losses, + such that each loss moves the atoms in the same direction. + + Args: + batch: Dictionary containing: + * atom14_gt_positions: Ground truth positions. + * atom14_alt_gt_positions: Ground truth positions with renaming swaps. + * atom14_atom_is_ambiguous: 1.0 for atoms that are affected by + renaming swaps. + * atom14_gt_exists: Mask for which atoms exist in ground truth. + * atom14_alt_gt_exists: Mask for which atoms exist in ground truth + after renaming. + * atom14_atom_exists: Mask for whether each atom is part of the given + amino acid type. + atom14_pred_positions: Array of atom positions in global frame with shape + Returns: + Dictionary containing: + alt_naming_is_better: Array with 1.0 where alternative swap is better. + renamed_atom14_gt_positions: Array of optimal ground truth positions + after renaming swaps are performed. + renamed_atom14_gt_exists: Mask after renaming swap is performed. + """ + + pred_dists = torch.sqrt( + eps + + torch.sum( + ( + atom14_pred_positions[..., None, :, None, :] + - atom14_pred_positions[..., None, :, None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + atom14_gt_positions = batch["atom14_gt_positions"] + gt_dists = torch.sqrt( + eps + + torch.sum( + ( + atom14_gt_positions[..., None, :, None, :] + - atom14_gt_positions[..., None, :, None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + atom14_alt_gt_positions = batch["atom14_alt_gt_positions"] + alt_gt_dists = torch.sqrt( + eps + + torch.sum( + ( + atom14_alt_gt_positions[..., None, :, None, :] + - atom14_alt_gt_positions[..., None, :, None, :, :] + ) + ** 2, + dim=-1, + ) + ) + + lddt = torch.sqrt(eps + (pred_dists - gt_dists) ** 2) + alt_lddt = torch.sqrt(eps + (pred_dists - alt_gt_dists) ** 2) + + atom14_gt_exists = batch["atom14_gt_exists"] + atom14_atom_is_ambiguous = batch["atom14_atom_is_ambiguous"] + mask = ( + atom14_gt_exists[..., None, :, None] + * atom14_atom_is_ambiguous[..., None, :, None] + * atom14_gt_exists[..., None, :, None, :] + * (1.0 - atom14_atom_is_ambiguous[..., None, :, None, :]) + ) + + per_res_lddt = torch.sum(mask * lddt, dim=(-1, -2, -3)) + alt_per_res_lddt = torch.sum(mask * alt_lddt, dim=(-1, -2, -3)) + + fp_type = atom14_pred_positions.dtype + alt_naming_is_better = (alt_per_res_lddt < per_res_lddt).type(fp_type) + + renamed_atom14_gt_positions = ( + 1.0 - alt_naming_is_better[..., None, None] + ) * atom14_gt_positions + alt_naming_is_better[ + ..., None, None + ] * atom14_alt_gt_positions + + renamed_atom14_gt_mask = ( + 1.0 - alt_naming_is_better[..., None] + ) * atom14_gt_exists + alt_naming_is_better[..., None] * batch[ + "atom14_alt_gt_exists" + ] + + return { + "alt_naming_is_better": alt_naming_is_better, + "renamed_atom14_gt_positions": renamed_atom14_gt_positions, + "renamed_atom14_gt_exists": renamed_atom14_gt_mask, + } + + +def experimentally_resolved_loss( + logits: torch.Tensor, + atom37_atom_exists: torch.Tensor, + all_atom_mask: torch.Tensor, + resolution: torch.Tensor, + min_resolution: float, + max_resolution: float, + eps: float = 1e-8, + **kwargs, +) -> torch.Tensor: + errors = sigmoid_cross_entropy(logits, all_atom_mask) + loss = torch.sum(errors * atom37_atom_exists, dim=-1) + loss = loss / (eps + torch.sum(atom37_atom_exists, dim=(-1, -2))) + loss = torch.sum(loss, dim=-1) + + loss = loss * ( + (resolution >= min_resolution) & (resolution <= max_resolution) + ) + + loss = torch.mean(loss) + + return loss + + +def masked_msa_loss(logits, true_msa, bert_mask, eps=1e-8, **kwargs): + """ + Computes BERT-style masked MSA loss. Implements subsection 1.9.9. + + Args: + logits: [*, N_seq, N_res, 23] predicted residue distribution + true_msa: [*, N_seq, N_res] true MSA + bert_mask: [*, N_seq, N_res] MSA mask + Returns: + Masked MSA loss + """ + errors = softmax_cross_entropy( + logits, torch.nn.functional.one_hot(true_msa, num_classes=23) + ) + + # FP16-friendly averaging. Equivalent to: + # loss = ( + # torch.sum(errors * bert_mask, dim=(-1, -2)) / + # (eps + torch.sum(bert_mask, dim=(-1, -2))) + # ) + loss = errors * bert_mask + loss = torch.sum(loss, dim=-1) + scale = 0.5 + denom = eps + torch.sum(scale * bert_mask, dim=(-1, -2)) + loss = loss / denom[..., None] + loss = torch.sum(loss, dim=-1) + loss = loss * scale + + loss = torch.mean(loss) + + return loss + + +def compute_drmsd(structure_1, structure_2, mask=None): + if(mask is not None): + structure_1 = structure_1 * mask[..., None] + structure_2 = structure_2 * mask[..., None] + + d1 = structure_1[..., :, None, :] - structure_1[..., None, :, :] + d2 = structure_2[..., :, None, :] - structure_2[..., None, :, :] + + d1 = d1 ** 2 + d2 = d2 ** 2 + + d1 = torch.sqrt(torch.sum(d1, dim=-1)) + d2 = torch.sqrt(torch.sum(d2, dim=-1)) + + drmsd = d1 - d2 + drmsd = drmsd ** 2 + drmsd = torch.sum(drmsd, dim=(-1, -2)) + n = d1.shape[-1] if mask is None else torch.sum(mask, dim=-1) + drmsd = drmsd * (1 / (n * (n - 1))) if n > 1 else (drmsd * 0.) + drmsd = torch.sqrt(drmsd) + + return drmsd + + +def compute_drmsd_np(structure_1, structure_2, mask=None): + structure_1 = torch.tensor(structure_1) + structure_2 = torch.tensor(structure_2) + if(mask is not None): + mask = torch.tensor(mask) + + return compute_drmsd(structure_1, structure_2, mask) + + +class AlphaFoldLoss(nn.Module): + """Aggregation of the various losses described in the supplement""" + def __init__(self, config): + super(AlphaFoldLoss, self).__init__() + self.config = config + + def forward(self, out, batch, _return_breakdown=False): + if "violation" not in out.keys(): + out["violation"] = find_structural_violations( + batch, + out["sm"]["positions"][-1], + **self.config.violation, + ) + + if "renamed_atom14_gt_positions" not in out.keys(): + batch.update( + compute_renamed_ground_truth( + batch, + out["sm"]["positions"][-1], + ) + ) + + loss_fns = { + "distogram": lambda: distogram_loss( + logits=out["distogram_logits"], + **{**batch, **self.config.distogram}, + ), + "experimentally_resolved": lambda: experimentally_resolved_loss( + logits=out["experimentally_resolved_logits"], + **{**batch, **self.config.experimentally_resolved}, + ), + "fape": lambda: fape_loss( + out, + batch, + self.config.fape, + ), + "lddt": lambda: lddt_loss( + logits=out["lddt_logits"], + all_atom_pred_pos=out["final_atom_positions"], + **{**batch, **self.config.lddt}, + ), + "masked_msa": lambda: masked_msa_loss( + logits=out["masked_msa_logits"], + **{**batch, **self.config.masked_msa}, + ), + "supervised_chi": lambda: supervised_chi_loss( + out["sm"]["angles"], + out["sm"]["unnormalized_angles"], + **{**batch, **self.config.supervised_chi}, + ), + "violation": lambda: violation_loss( + out["violation"], + **batch, + ), + } + + if(self.config.tm.enabled): + loss_fns["tm"] = lambda: tm_loss( + logits=out["tm_logits"], + **{**batch, **out, **self.config.tm}, + ) + + cum_loss = 0. + losses = {} + for loss_name, loss_fn in loss_fns.items(): + weight = self.config[loss_name].weight + loss = loss_fn() + if(torch.isnan(loss) or torch.isinf(loss)): + logging.warning(f"{loss_name} loss is NaN. Skipping...") + loss = loss.new_tensor(0., requires_grad=True) + cum_loss = cum_loss + weight * loss + losses[loss_name] = loss.detach().clone() + + losses["unscaled_loss"] = cum_loss.detach().clone() + + # Scale the loss by the square root of the minimum of the crop size and + # the (average) sequence length. See subsection 1.9. + seq_len = torch.mean(batch["seq_length"].float()) + crop_len = batch["aatype"].shape[-1] + cum_loss = cum_loss * torch.sqrt(min(seq_len, crop_len)) + + losses["loss"] = cum_loss.detach().clone() + + if(not _return_breakdown): + return cum_loss + + return cum_loss, losses diff --git a/gafl/openfold/utils/lr_schedulers.py b/gafl/openfold/utils/lr_schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..5d068be5ec826e7d1f8d49b3459b7cc66547f9f8 --- /dev/null +++ b/gafl/openfold/utils/lr_schedulers.py @@ -0,0 +1,107 @@ +import torch + + +class AlphaFoldLRScheduler(torch.optim.lr_scheduler._LRScheduler): + """ Implements the learning rate schedule defined in the AlphaFold 2 + supplement. A linear warmup is followed by a plateau at the maximum + learning rate and then exponential decay. + + Note that the initial learning rate of the optimizer in question is + ignored; use this class' base_lr parameter to specify the starting + point of the warmup. + """ + def __init__(self, + optimizer, + last_epoch: int = -1, + verbose: bool = False, + base_lr: float = 0., + max_lr: float = 0.001, + warmup_no_steps: int = 1000, + start_decay_after_n_steps: int = 50000, + decay_every_n_steps: int = 50000, + decay_factor: float = 0.95, + ): + step_counts = { + "warmup_no_steps": warmup_no_steps, + "start_decay_after_n_steps": start_decay_after_n_steps, + } + + for k,v in step_counts.items(): + if(v < 0): + raise ValueError(f"{k} must be nonnegative") + + if(warmup_no_steps > start_decay_after_n_steps): + raise ValueError( + "warmup_no_steps must not exceed start_decay_after_n_steps" + ) + + self.optimizer = optimizer + self.last_epoch = last_epoch + self.verbose = verbose + self.base_lr = base_lr + self.max_lr = max_lr + self.warmup_no_steps = warmup_no_steps + self.start_decay_after_n_steps = start_decay_after_n_steps + self.decay_every_n_steps = decay_every_n_steps + self.decay_factor = decay_factor + + super(AlphaFoldLRScheduler, self).__init__( + optimizer, + last_epoch=last_epoch, + verbose=verbose, + ) + + def state_dict(self): + state_dict = { + k:v for k,v in self.__dict__.items() if k not in ["optimizer"] + } + + return state_dict + + def load_state_dict(self, state_dict): + self.__dict__.update(state_dict) + + def get_lr(self): + if(not self._get_lr_called_within_step): + raise RuntimeError( + "To get the last learning rate computed by the scheduler, use " + "get_last_lr()" + ) + + step_no = self.last_epoch + + if(step_no <= self.warmup_no_steps): + lr = self.base_lr + (step_no / self.warmup_no_steps) * self.max_lr + elif(step_no > self.start_decay_after_n_steps): + steps_since_decay = step_no - self.start_decay_after_n_steps + exp = (steps_since_decay // self.decay_every_n_steps) + 1 + lr = self.max_lr * (self.decay_factor ** exp) + else: # plateau + lr = self.max_lr + + return [lr for group in self.optimizer.param_groups] + + +class TestAF2LRScheduler(AlphaFoldLRScheduler): + def __init__(self, + optimizer, + last_epoch: int = -1, + verbose: bool = False, + base_lr: float = 0., + max_lr: float = 0.0001, + warmup_no_steps: int = 10, + start_decay_after_n_steps: int = 100, + decay_every_n_steps: int = 10, + decay_factor: float = 0.95, + ): + super().__init__( + optimizer, + last_epoch, + verbose, + base_lr, + max_lr, + warmup_no_steps, + start_decay_after_n_steps, + decay_every_n_steps, + decay_factor, + ) \ No newline at end of file diff --git a/gafl/openfold/utils/precision_utils.py b/gafl/openfold/utils/precision_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..81ef568637a1f6ee30a8fc295edbb60a70f4c602 --- /dev/null +++ b/gafl/openfold/utils/precision_utils.py @@ -0,0 +1,23 @@ +# Copyright 2022 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import importlib + +import torch + +def is_fp16_enabled(): + # Autocast world + fp16_enabled = torch.get_autocast_gpu_dtype() == torch.float16 + fp16_enabled = fp16_enabled and torch.is_autocast_enabled() + + return fp16_enabled diff --git a/gafl/openfold/utils/rigid_utils.py b/gafl/openfold/utils/rigid_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..62fa8f284f76a46e5dbb1b64f3b0e319b6c09b70 --- /dev/null +++ b/gafl/openfold/utils/rigid_utils.py @@ -0,0 +1,1479 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# Copyright 2024 HITS gGmbH +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Tuple, Any, Sequence, Callable, Optional +from gafl.data.quarternion_utils import rot_to_quat + +import numpy as np +import torch + + +def rot_matmul( + a: torch.Tensor, + b: torch.Tensor +) -> torch.Tensor: + """ + Performs matrix multiplication of two rotation matrix tensors. Written + out by hand to avoid AMP downcasting. + + Args: + a: [*, 3, 3] left multiplicand + b: [*, 3, 3] right multiplicand + Returns: + The product ab + """ + row_1 = torch.stack( + [ + a[..., 0, 0] * b[..., 0, 0] + + a[..., 0, 1] * b[..., 1, 0] + + a[..., 0, 2] * b[..., 2, 0], + a[..., 0, 0] * b[..., 0, 1] + + a[..., 0, 1] * b[..., 1, 1] + + a[..., 0, 2] * b[..., 2, 1], + a[..., 0, 0] * b[..., 0, 2] + + a[..., 0, 1] * b[..., 1, 2] + + a[..., 0, 2] * b[..., 2, 2], + ], + dim=-1, + ) + row_2 = torch.stack( + [ + a[..., 1, 0] * b[..., 0, 0] + + a[..., 1, 1] * b[..., 1, 0] + + a[..., 1, 2] * b[..., 2, 0], + a[..., 1, 0] * b[..., 0, 1] + + a[..., 1, 1] * b[..., 1, 1] + + a[..., 1, 2] * b[..., 2, 1], + a[..., 1, 0] * b[..., 0, 2] + + a[..., 1, 1] * b[..., 1, 2] + + a[..., 1, 2] * b[..., 2, 2], + ], + dim=-1, + ) + row_3 = torch.stack( + [ + a[..., 2, 0] * b[..., 0, 0] + + a[..., 2, 1] * b[..., 1, 0] + + a[..., 2, 2] * b[..., 2, 0], + a[..., 2, 0] * b[..., 0, 1] + + a[..., 2, 1] * b[..., 1, 1] + + a[..., 2, 2] * b[..., 2, 1], + a[..., 2, 0] * b[..., 0, 2] + + a[..., 2, 1] * b[..., 1, 2] + + a[..., 2, 2] * b[..., 2, 2], + ], + dim=-1, + ) + + return torch.stack([row_1, row_2, row_3], dim=-2) + + +def rot_vec_mul( + r: torch.Tensor, + t: torch.Tensor +) -> torch.Tensor: + """ + Applies a rotation to a vector. Written out by hand to avoid transfer + to avoid AMP downcasting. + + Args: + r: [*, 3, 3] rotation matrices + t: [*, 3] coordinate tensors + Returns: + [*, 3] rotated coordinates + """ + x = t[..., 0] + y = t[..., 1] + z = t[..., 2] + return torch.stack( + [ + r[..., 0, 0] * x + r[..., 0, 1] * y + r[..., 0, 2] * z, + r[..., 1, 0] * x + r[..., 1, 1] * y + r[..., 1, 2] * z, + r[..., 2, 0] * x + r[..., 2, 1] * y + r[..., 2, 2] * z, + ], + dim=-1, + ) + + +def identity_rot_mats( + batch_dims: Tuple[int], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + requires_grad: bool = True, +) -> torch.Tensor: + rots = torch.eye( + 3, dtype=dtype, device=device, requires_grad=requires_grad + ) + rots = rots.view(*((1,) * len(batch_dims)), 3, 3) + rots = rots.expand(*batch_dims, -1, -1) + + return rots + + +def identity_trans( + batch_dims: Tuple[int], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + requires_grad: bool = True, +) -> torch.Tensor: + trans = torch.zeros( + (*batch_dims, 3), + dtype=dtype, + device=device, + requires_grad=requires_grad + ) + return trans + + +def identity_quats( + batch_dims: Tuple[int], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + requires_grad: bool = True, +) -> torch.Tensor: + quat = torch.zeros( + (*batch_dims, 4), + dtype=dtype, + device=device, + requires_grad=requires_grad + ) + + with torch.no_grad(): + quat[..., 0] = 1 + + return quat + + +_quat_elements = ["a", "b", "c", "d"] +_qtr_keys = [l1 + l2 for l1 in _quat_elements for l2 in _quat_elements] +_qtr_ind_dict = {key: ind for ind, key in enumerate(_qtr_keys)} + + +def _to_mat(pairs): + mat = np.zeros((4, 4)) + for pair in pairs: + key, value = pair + ind = _qtr_ind_dict[key] + mat[ind // 4][ind % 4] = value + + return mat + + +_QTR_MAT = np.zeros((4, 4, 3, 3)) +_QTR_MAT[..., 0, 0] = _to_mat([("aa", 1), ("bb", 1), ("cc", -1), ("dd", -1)]) +_QTR_MAT[..., 0, 1] = _to_mat([("bc", 2), ("ad", -2)]) +_QTR_MAT[..., 0, 2] = _to_mat([("bd", 2), ("ac", 2)]) +_QTR_MAT[..., 1, 0] = _to_mat([("bc", 2), ("ad", 2)]) +_QTR_MAT[..., 1, 1] = _to_mat([("aa", 1), ("bb", -1), ("cc", 1), ("dd", -1)]) +_QTR_MAT[..., 1, 2] = _to_mat([("cd", 2), ("ab", -2)]) +_QTR_MAT[..., 2, 0] = _to_mat([("bd", 2), ("ac", -2)]) +_QTR_MAT[..., 2, 1] = _to_mat([("cd", 2), ("ab", 2)]) +_QTR_MAT[..., 2, 2] = _to_mat([("aa", 1), ("bb", -1), ("cc", -1), ("dd", 1)]) + + +def quat_to_rot(quat: torch.Tensor) -> torch.Tensor: + """ + Converts a quaternion to a rotation matrix. + + Args: + quat: [*, 4] quaternions + Returns: + [*, 3, 3] rotation matrices + """ + # [*, 4, 4] + quat = quat[..., None] * quat[..., None, :] + + # [4, 4, 3, 3] + mat = quat.new_tensor(_QTR_MAT, requires_grad=False) + + # [*, 4, 4, 3, 3] + shaped_qtr_mat = mat.view((1,) * len(quat.shape[:-2]) + mat.shape) + quat = quat[..., None, None] * shaped_qtr_mat + + # [*, 3, 3] + return torch.sum(quat, dim=(-3, -4)) + + +# def rot_to_quat( +# rot: torch.Tensor, +# ): +# if(rot.shape[-2:] != (3, 3)): +# raise ValueError("Input rotation is incorrectly shaped") + +# rot = [[rot[..., i, j] for j in range(3)] for i in range(3)] +# [[xx, xy, xz], [yx, yy, yz], [zx, zy, zz]] = rot + +# k = [ +# [ xx + yy + zz, zy - yz, xz - zx, yx - xy,], +# [ zy - yz, xx - yy - zz, xy + yx, xz + zx,], +# [ xz - zx, xy + yx, yy - xx - zz, yz + zy,], +# [ yx - xy, xz + zx, yz + zy, zz - xx - yy,] +# ] + +# k = (1./3.) * torch.stack([torch.stack(t, dim=-1) for t in k], dim=-2) + +# _, vectors = torch.linalg.eigh(k) +# return vectors[..., -1] + + +_QUAT_MULTIPLY = np.zeros((4, 4, 4)) +_QUAT_MULTIPLY[:, :, 0] = [[ 1, 0, 0, 0], + [ 0,-1, 0, 0], + [ 0, 0,-1, 0], + [ 0, 0, 0,-1]] + +_QUAT_MULTIPLY[:, :, 1] = [[ 0, 1, 0, 0], + [ 1, 0, 0, 0], + [ 0, 0, 0, 1], + [ 0, 0,-1, 0]] + +_QUAT_MULTIPLY[:, :, 2] = [[ 0, 0, 1, 0], + [ 0, 0, 0,-1], + [ 1, 0, 0, 0], + [ 0, 1, 0, 0]] + +_QUAT_MULTIPLY[:, :, 3] = [[ 0, 0, 0, 1], + [ 0, 0, 1, 0], + [ 0,-1, 0, 0], + [ 1, 0, 0, 0]] + +_QUAT_MULTIPLY_BY_VEC = _QUAT_MULTIPLY[:, 1:, :] + + +def quat_multiply(quat1, quat2): + """Multiply a quaternion by another quaternion.""" + mat = quat1.new_tensor(_QUAT_MULTIPLY) + reshaped_mat = mat.view((1,) * len(quat1.shape[:-1]) + mat.shape) + return torch.sum( + reshaped_mat * + quat1[..., :, None, None] * + quat2[..., None, :, None], + dim=(-3, -2) + ) + + +def quat_multiply_by_vec(quat, vec): + """Multiply a quaternion by a pure-vector quaternion.""" + mat = quat.new_tensor(_QUAT_MULTIPLY_BY_VEC) + reshaped_mat = mat.view((1,) * len(quat.shape[:-1]) + mat.shape) + return torch.sum( + reshaped_mat * + quat[..., :, None, None] * + vec[..., None, :, None], + dim=(-3, -2) + ) + + +def invert_rot_mat(rot_mat: torch.Tensor): + return rot_mat.transpose(-1, -2) + + +def invert_quat(quat: torch.Tensor): + quat_prime = quat.clone() + quat_prime[..., 1:] *= -1 + inv = quat_prime / torch.sum(quat ** 2, dim=-1, keepdim=True) + return inv + + +class Rotation: + """ + A 3D rotation. Depending on how the object is initialized, the + rotation is represented by either a rotation matrix or a + quaternion, though both formats are made available by helper functions. + To simplify gradient computation, the underlying format of the + rotation cannot be changed in-place. Like Rigid, the class is designed + to mimic the behavior of a torch Tensor, almost as if each Rotation + object were a tensor of rotations, in one format or another. + """ + def __init__(self, + rot_mats: Optional[torch.Tensor] = None, + quats: Optional[torch.Tensor] = None, + normalize_quats: bool = True, + ): + """ + Args: + rot_mats: + A [*, 3, 3] rotation matrix tensor. Mutually exclusive with + quats + quats: + A [*, 4] quaternion. Mutually exclusive with rot_mats. If + normalize_quats is not True, must be a unit quaternion + normalize_quats: + If quats is specified, whether to normalize quats + """ + if((rot_mats is None and quats is None) or + (rot_mats is not None and quats is not None)): + raise ValueError("Exactly one input argument must be specified") + + if((rot_mats is not None and rot_mats.shape[-2:] != (3, 3)) or + (quats is not None and quats.shape[-1] != 4)): + raise ValueError( + "Incorrectly shaped rotation matrix or quaternion" + ) + + # Force full-precision + if(quats is not None): + quats = quats.type(torch.float32) + if(rot_mats is not None): + rot_mats = rot_mats.type(torch.float32) + + if(quats is not None and normalize_quats): + quats = quats / torch.linalg.norm(quats, dim=-1, keepdim=True) + + self._rot_mats = rot_mats + self._quats = quats + + @staticmethod + def identity( + shape, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + requires_grad: bool = True, + fmt: str = "quat", + ): + """ + Returns an identity Rotation. + + Args: + shape: + The "shape" of the resulting Rotation object. See documentation + for the shape property + dtype: + The torch dtype for the rotation + device: + The torch device for the new rotation + requires_grad: + Whether the underlying tensors in the new rotation object + should require gradient computation + fmt: + One of "quat" or "rot_mat". Determines the underlying format + of the new object's rotation + Returns: + A new identity rotation + """ + if(fmt == "rot_mat"): + rot_mats = identity_rot_mats( + shape, dtype, device, requires_grad, + ) + return Rotation(rot_mats=rot_mats, quats=None) + elif(fmt == "quat"): + quats = identity_quats(shape, dtype, device, requires_grad) + return Rotation(rot_mats=None, quats=quats, normalize_quats=False) + else: + raise ValueError(f"Invalid format: f{fmt}") + + # Magic methods + + def __getitem__(self, index: Any): + """ + Allows torch-style indexing over the virtual shape of the rotation + object. See documentation for the shape property. + + Args: + index: + A torch index. E.g. (1, 3, 2), or (slice(None,)) + Returns: + The indexed rotation + """ + if type(index) != tuple: + index = (index,) + + if(self._rot_mats is not None): + rot_mats = self._rot_mats[index + (slice(None), slice(None))] + return Rotation(rot_mats=rot_mats) + elif(self._quats is not None): + quats = self._quats[index + (slice(None),)] + return Rotation(quats=quats, normalize_quats=False) + else: + raise ValueError("Both rotations are None") + + def __mul__(self, + right: torch.Tensor, + ): + """ + Pointwise left multiplication of the rotation with a tensor. Can be + used to e.g. mask the Rotation. + + Args: + right: + The tensor multiplicand + Returns: + The product + """ + if not(isinstance(right, torch.Tensor)): + raise TypeError("The other multiplicand must be a Tensor") + + if(self._rot_mats is not None): + rot_mats = self._rot_mats * right[..., None, None] + return Rotation(rot_mats=rot_mats, quats=None) + elif(self._quats is not None): + quats = self._quats * right[..., None] + return Rotation(rot_mats=None, quats=quats, normalize_quats=False) + else: + raise ValueError("Both rotations are None") + + def __rmul__(self, + left: torch.Tensor, + ): + """ + Reverse pointwise multiplication of the rotation with a tensor. + + Args: + left: + The left multiplicand + Returns: + The product + """ + return self.__mul__(left) + + # Properties + + @property + def shape(self) -> torch.Size: + """ + Returns the virtual shape of the rotation object. This shape is + defined as the batch dimensions of the underlying rotation matrix + or quaternion. If the Rotation was initialized with a [10, 3, 3] + rotation matrix tensor, for example, the resulting shape would be + [10]. + + Returns: + The virtual shape of the rotation object + """ + s = None + if(self._quats is not None): + s = self._quats.shape[:-1] + else: + s = self._rot_mats.shape[:-2] + + return s + + @property + def dtype(self) -> torch.dtype: + """ + Returns the dtype of the underlying rotation. + + Returns: + The dtype of the underlying rotation + """ + if(self._rot_mats is not None): + return self._rot_mats.dtype + elif(self._quats is not None): + return self._quats.dtype + else: + raise ValueError("Both rotations are None") + + @property + def device(self) -> torch.device: + """ + The device of the underlying rotation + + Returns: + The device of the underlying rotation + """ + if(self._rot_mats is not None): + return self._rot_mats.device + elif(self._quats is not None): + return self._quats.device + else: + raise ValueError("Both rotations are None") + + @property + def requires_grad(self) -> bool: + """ + Returns the requires_grad property of the underlying rotation + + Returns: + The requires_grad property of the underlying tensor + """ + if(self._rot_mats is not None): + return self._rot_mats.requires_grad + elif(self._quats is not None): + return self._quats.requires_grad + else: + raise ValueError("Both rotations are None") + + def get_rot_mats(self) -> torch.Tensor: + """ + Returns the underlying rotation as a rotation matrix tensor. + + Returns: + The rotation as a rotation matrix tensor + """ + rot_mats = self._rot_mats + if(rot_mats is None): + if(self._quats is None): + raise ValueError("Both rotations are None") + else: + rot_mats = quat_to_rot(self._quats) + + return rot_mats + + def get_quats(self) -> torch.Tensor: + """ + Returns the underlying rotation as a quaternion tensor. + + Depending on whether the Rotation was initialized with a + quaternion, this function may call torch.linalg.eigh. + + Returns: + The rotation as a quaternion tensor. + """ + quats = self._quats + if(quats is None): + if(self._rot_mats is None): + raise ValueError("Both rotations are None") + else: + quats = rot_to_quat(self._rot_mats) + + return quats + + def get_cur_rot(self) -> torch.Tensor: + """ + Return the underlying rotation in its current form + + Returns: + The stored rotation + """ + if(self._rot_mats is not None): + return self._rot_mats + elif(self._quats is not None): + return self._quats + else: + raise ValueError("Both rotations are None") + + def get_rotvec(self, eps=1e-6) -> torch.Tensor: + """ + Return the underlying axis-angle rotation vector. + + Follow's scipy's implementation: + https://github.com/scipy/scipy/blob/HEAD/scipy/spatial/transform/_rotation.pyx#L1385-L1402 + + Returns: + The stored rotation as a axis-angle vector. + """ + quat = self.get_quats() + # w > 0 to ensure 0 <= angle <= pi + flip = (quat[..., :1] < 0).float() + quat = (-1 * quat) * flip + (1 - flip) * quat + + angle = 2 * torch.atan2( + torch.linalg.norm(quat[..., 1:], dim=-1), + quat[..., 0] + ) + + angle2 = angle * angle + small_angle_scales = 2 + angle2 / 12 + 7 * angle2 * angle2 / 2880 + large_angle_scales = angle / torch.sin(angle / 2 + eps) + + small_angles = (angle <= 1e-3).float() + rot_vec_scale = small_angle_scales * small_angles + (1 - small_angles) * large_angle_scales + rot_vec = rot_vec_scale[..., None] * quat[..., 1:] + return rot_vec + + # Rotation functions + + def compose_q_update_vec(self, + q_update_vec: torch.Tensor, + normalize_quats: bool = True, + update_mask: torch.Tensor = None, + ): + """ + Returns a new quaternion Rotation after updating the current + object's underlying rotation with a quaternion update, formatted + as a [*, 3] tensor whose final three columns represent x, y, z such + that (1, x, y, z) is the desired (not necessarily unit) quaternion + update. + + Args: + q_update_vec: + A [*, 3] quaternion update tensor + normalize_quats: + Whether to normalize the output quaternion + Returns: + An updated Rotation + """ + quats = self.get_quats() + quat_update = quat_multiply_by_vec(quats, q_update_vec) + if update_mask is not None: + quat_update = quat_update * update_mask + new_quats = quats + quat_update + return Rotation( + rot_mats=None, + quats=new_quats, + normalize_quats=normalize_quats, + ) + + def compose_r(self, r): + """ + Compose the rotation matrices of the current Rotation object with + those of another. + + Args: + r: + An update rotation object + Returns: + An updated rotation object + """ + r1 = self.get_rot_mats() + r2 = r.get_rot_mats() + new_rot_mats = rot_matmul(r1, r2) + return Rotation(rot_mats=new_rot_mats, quats=None) + + def compose_q(self, r, normalize_quats: bool = True): + """ + Compose the quaternions of the current Rotation object with those + of another. + + Depending on whether either Rotation was initialized with + quaternions, this function may call torch.linalg.eigh. + + Args: + r: + An update rotation object + Returns: + An updated rotation object + """ + q1 = self.get_quats() + q2 = r.get_quats() + new_quats = quat_multiply(q1, q2) + return Rotation( + rot_mats=None, quats=new_quats, normalize_quats=normalize_quats + ) + + def apply(self, pts: torch.Tensor) -> torch.Tensor: + """ + Apply the current Rotation as a rotation matrix to a set of 3D + coordinates. + + Args: + pts: + A [*, 3] set of points + Returns: + [*, 3] rotated points + """ + rot_mats = self.get_rot_mats() + return rot_vec_mul(rot_mats, pts) + + def invert_apply(self, pts: torch.Tensor) -> torch.Tensor: + """ + The inverse of the apply() method. + + Args: + pts: + A [*, 3] set of points + Returns: + [*, 3] inverse-rotated points + """ + rot_mats = self.get_rot_mats() + inv_rot_mats = invert_rot_mat(rot_mats) + return rot_vec_mul(inv_rot_mats, pts) + + def invert(self) : + """ + Returns the inverse of the current Rotation. + + Returns: + The inverse of the current Rotation + """ + if(self._rot_mats is not None): + return Rotation( + rot_mats=invert_rot_mat(self._rot_mats), + quats=None + ) + elif(self._quats is not None): + return Rotation( + rot_mats=None, + quats=invert_quat(self._quats), + normalize_quats=False, + ) + else: + raise ValueError("Both rotations are None") + + # "Tensor" stuff + + def unsqueeze(self, + dim: int, + ): + """ + Analogous to torch.unsqueeze. The dimension is relative to the + shape of the Rotation object. + + Args: + dim: A positive or negative dimension index. + Returns: + The unsqueezed Rotation. + """ + if dim >= len(self.shape): + raise ValueError("Invalid dimension") + + if(self._rot_mats is not None): + rot_mats = self._rot_mats.unsqueeze(dim if dim >= 0 else dim - 2) + return Rotation(rot_mats=rot_mats, quats=None) + elif(self._quats is not None): + quats = self._quats.unsqueeze(dim if dim >= 0 else dim - 1) + return Rotation(rot_mats=None, quats=quats, normalize_quats=False) + else: + raise ValueError("Both rotations are None") + + @staticmethod + def cat( + rs, + dim: int, + ): + """ + Concatenates rotations along one of the batch dimensions. Analogous + to torch.cat(). + + Note that the output of this operation is always a rotation matrix, + regardless of the format of input rotations. + + Args: + rs: + A list of rotation objects + dim: + The dimension along which the rotations should be + concatenated + Returns: + A concatenated Rotation object in rotation matrix format + """ + rot_mats = [r.get_rot_mats() for r in rs] + rot_mats = torch.cat(rot_mats, dim=dim if dim >= 0 else dim - 2) + + return Rotation(rot_mats=rot_mats, quats=None) + + def map_tensor_fn(self, + fn + ): + """ + Apply a Tensor -> Tensor function to underlying rotation tensors, + mapping over the rotation dimension(s). Can be used e.g. to sum out + a one-hot batch dimension. + + Args: + fn: + A Tensor -> Tensor function to be mapped over the Rotation + Returns: + The transformed Rotation object + """ + if(self._rot_mats is not None): + rot_mats = self._rot_mats.view(self._rot_mats.shape[:-2] + (9,)) + rot_mats = torch.stack( + list(map(fn, torch.unbind(rot_mats, dim=-1))), dim=-1 + ) + rot_mats = rot_mats.view(rot_mats.shape[:-1] + (3, 3)) + return Rotation(rot_mats=rot_mats, quats=None) + elif(self._quats is not None): + quats = torch.stack( + list(map(fn, torch.unbind(self._quats, dim=-1))), dim=-1 + ) + return Rotation(rot_mats=None, quats=quats, normalize_quats=False) + else: + raise ValueError("Both rotations are None") + + def cuda(self): + """ + Analogous to the cuda() method of torch Tensors + + Returns: + A copy of the Rotation in CUDA memory + """ + if(self._rot_mats is not None): + return Rotation(rot_mats=self._rot_mats.cuda(), quats=None) + elif(self._quats is not None): + return Rotation( + rot_mats=None, + quats=self._quats.cuda(), + normalize_quats=False + ) + else: + raise ValueError("Both rotations are None") + + def to(self, + device: Optional[torch.device], + dtype: Optional[torch.dtype] + ): + """ + Analogous to the to() method of torch Tensors + + Args: + device: + A torch device + dtype: + A torch dtype + Returns: + A copy of the Rotation using the new device and dtype + """ + if(self._rot_mats is not None): + return Rotation( + rot_mats=self._rot_mats.to(device=device, dtype=dtype), + quats=None, + ) + elif(self._quats is not None): + return Rotation( + rot_mats=None, + quats=self._quats.to(device=device, dtype=dtype), + normalize_quats=False, + ) + else: + raise ValueError("Both rotations are None") + + def detach(self): + """ + Returns a copy of the Rotation whose underlying Tensor has been + detached from its torch graph. + + Returns: + A copy of the Rotation whose underlying Tensor has been detached + from its torch graph + """ + if(self._rot_mats is not None): + return Rotation(rot_mats=self._rot_mats.detach(), quats=None) + elif(self._quats is not None): + return Rotation( + rot_mats=None, + quats=self._quats.detach(), + normalize_quats=False, + ) + else: + raise ValueError("Both rotations are None") + + +class Rigid: + """ + A class representing a rigid transformation. Little more than a wrapper + around two objects: a Rotation object and a [*, 3] translation + Designed to behave approximately like a single torch tensor with the + shape of the shared batch dimensions of its component parts. + """ + def __init__(self, + rots: Optional[Rotation], + trans: Optional[torch.Tensor], + ): + """ + Args: + rots: A [*, 3, 3] rotation tensor + trans: A corresponding [*, 3] translation tensor + """ + # (we need device, dtype, etc. from at least one input) + + batch_dims, dtype, device, requires_grad = None, None, None, None + if(trans is not None): + batch_dims = trans.shape[:-1] + dtype = trans.dtype + device = trans.device + requires_grad = trans.requires_grad + elif(rots is not None): + batch_dims = rots.shape + dtype = rots.dtype + device = rots.device + requires_grad = rots.requires_grad + else: + raise ValueError("At least one input argument must be specified") + + if(rots is None): + rots = Rotation.identity( + batch_dims, dtype, device, requires_grad, + ) + elif(trans is None): + trans = identity_trans( + batch_dims, dtype, device, requires_grad, + ) + + if((rots.shape != trans.shape[:-1]) or + (rots.device != trans.device)): + raise ValueError("Rots and trans incompatible") + + # Force full precision. Happens to the rotations automatically. + trans = trans.type(torch.float32) + + self._rots = rots + self._trans = trans + + @staticmethod + def identity( + shape: Tuple[int], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + requires_grad: bool = True, + fmt: str = "quat", + ): + """ + Constructs an identity transformation. + + Args: + shape: + The desired shape + dtype: + The dtype of both internal tensors + device: + The device of both internal tensors + requires_grad: + Whether grad should be enabled for the internal tensors + Returns: + The identity transformation + """ + return Rigid( + Rotation.identity(shape, dtype, device, requires_grad, fmt=fmt), + identity_trans(shape, dtype, device, requires_grad), + ) + + def __getitem__(self, + index: Any, + ): + """ + Indexes the affine transformation with PyTorch-style indices. + The index is applied to the shared dimensions of both the rotation + and the translation. + + E.g.:: + + r = Rotation(rot_mats=torch.rand(10, 10, 3, 3), quats=None) + t = Rigid(r, torch.rand(10, 10, 3)) + indexed = t[3, 4:6] + assert(indexed.shape == (2,)) + assert(indexed.get_rots().shape == (2,)) + assert(indexed.get_trans().shape == (2, 3)) + + Args: + index: A standard torch tensor index. E.g. 8, (10, None, 3), + or (3, slice(0, 1, None)) + Returns: + The indexed tensor + """ + if type(index) != tuple: + index = (index,) + + return Rigid( + self._rots[index], + self._trans[index + (slice(None),)], + ) + + def __mul__(self, + right: torch.Tensor, + ): + """ + Pointwise left multiplication of the transformation with a tensor. + Can be used to e.g. mask the Rigid. + + Args: + right: + The tensor multiplicand + Returns: + The product + """ + if not(isinstance(right, torch.Tensor)): + raise TypeError("The other multiplicand must be a Tensor") + + new_rots = self._rots * right + new_trans = self._trans * right[..., None] + + return Rigid(new_rots, new_trans) + + def __rmul__(self, + left: torch.Tensor, + ): + """ + Reverse pointwise multiplication of the transformation with a + tensor. + + Args: + left: + The left multiplicand + Returns: + The product + """ + return self.__mul__(left) + + @property + def shape(self) -> torch.Size: + """ + Returns the shape of the shared dimensions of the rotation and + the translation. + + Returns: + The shape of the transformation + """ + s = self._trans.shape[:-1] + return s + + @property + def device(self) -> torch.device: + """ + Returns the device on which the Rigid's tensors are located. + + Returns: + The device on which the Rigid's tensors are located + """ + return self._trans.device + + def get_rots(self) -> Rotation: + """ + Getter for the rotation. + + Returns: + The rotation object + """ + return self._rots + + def get_trans(self) -> torch.Tensor: + """ + Getter for the translation. + + Returns: + The stored translation + """ + return self._trans + + def compose_q_update_vec(self, + q_update_vec: torch.Tensor, + update_mask: torch.Tensor=None, + ): + """ + Composes the transformation with a quaternion update vector of + shape [*, 6], where the final 6 columns represent the x, y, and + z values of a quaternion of form (1, x, y, z) followed by a 3D + translation. + + Args: + q_vec: The quaternion update vector. + Returns: + The composed transformation. + """ + q_vec, t_vec = q_update_vec[..., :3], q_update_vec[..., 3:] + new_rots = self._rots.compose_q_update_vec( + q_vec, update_mask=update_mask) + + trans_update = self._rots.apply(t_vec) + if update_mask is not None: + trans_update = trans_update * update_mask + new_translation = self._trans + trans_update + + return Rigid(new_rots, new_translation) + + def compose_tran_update_vec(self, + t_vec: torch.Tensor, + update_mask: torch.Tensor=None, + ): + """ + Composes the transformation with a quaternion update vector of + shape [*, 3], where columns represent a 3D translation. + + Args: + q_vec: The quaternion update vector. + Returns: + The composed transformation. + """ + trans_update = self._rots.apply(t_vec) + if update_mask is not None: + trans_update = trans_update * update_mask + new_translation = self._trans + trans_update + + return Rigid(self._rots, new_translation) + + def compose(self, + r, + ): + """ + Composes the current rigid object with another. + + Args: + r: + Another Rigid object + Returns: + The composition of the two transformations + """ + new_rot = self._rots.compose_r(r._rots) + new_trans = self._rots.apply(r._trans) + self._trans + return Rigid(new_rot, new_trans) + + # Copied from VFN repo #################################### + def decompose(self, + r, + ): + new_rot = self._rots.invert().compose_r(r._rots) + new_trans = self._rots.invert_apply(r._trans-self._trans) + return Rigid(new_rot, new_trans) + ########################################################### + + def compose_r(self, + rot, + order='right' + ): + """ + Composes the current rigid object with another. + + Args: + r: + Another Rigid object + order: + Order in which to perform rotation multiplication. + Returns: + The composition of the two transformations + """ + if order == 'right': + new_rot = self._rots.compose_r(rot) + elif order == 'left': + new_rot = rot.compose_r(self._rots) + else: + raise ValueError(f'Unrecognized multiplication order: {order}') + return Rigid(new_rot, self._trans) + + def apply(self, + pts: torch.Tensor, + ) -> torch.Tensor: + """ + Applies the transformation to a coordinate tensor. + + Args: + pts: A [*, 3] coordinate tensor. + Returns: + The transformed points. + """ + rotated = self._rots.apply(pts) + return rotated + self._trans + + def invert_apply(self, + pts: torch.Tensor + ) -> torch.Tensor: + """ + Applies the inverse of the transformation to a coordinate tensor. + + Args: + pts: A [*, 3] coordinate tensor + Returns: + The transformed points. + """ + pts = pts - self._trans + return self._rots.invert_apply(pts) + + def invert(self): + """ + Inverts the transformation. + + Returns: + The inverse transformation. + """ + rot_inv = self._rots.invert() + trn_inv = rot_inv.apply(self._trans) + + return Rigid(rot_inv, -1 * trn_inv) + + def map_tensor_fn(self, + fn + ): + """ + Apply a Tensor -> Tensor function to underlying translation and + rotation tensors, mapping over the translation/rotation dimensions + respectively. + + Args: + fn: + A Tensor -> Tensor function to be mapped over the Rigid + Returns: + The transformed Rigid object + """ + new_rots = self._rots.map_tensor_fn(fn) + new_trans = torch.stack( + list(map(fn, torch.unbind(self._trans, dim=-1))), + dim=-1 + ) + + return Rigid(new_rots, new_trans) + + def to_tensor_4x4(self) -> torch.Tensor: + """ + Converts a transformation to a homogenous transformation tensor. + + Returns: + A [*, 4, 4] homogenous transformation tensor + """ + tensor = self._trans.new_zeros((*self.shape, 4, 4)) + tensor[..., :3, :3] = self._rots.get_rot_mats() + tensor[..., :3, 3] = self._trans + tensor[..., 3, 3] = 1 + return tensor + + @staticmethod + def from_tensor_4x4( + t: torch.Tensor + ): + """ + Constructs a transformation from a homogenous transformation + tensor. + + Args: + t: [*, 4, 4] homogenous transformation tensor + Returns: + T object with shape [*] + """ + if(t.shape[-2:] != (4, 4)): + raise ValueError("Incorrectly shaped input tensor") + + rots = Rotation(rot_mats=t[..., :3, :3], quats=None) + trans = t[..., :3, 3] + + return Rigid(rots, trans) + + def to_tensor_7(self) -> torch.Tensor: + """ + Converts a transformation to a tensor with 7 final columns, four + for the quaternion followed by three for the translation. + + Returns: + A [*, 7] tensor representation of the transformation + """ + tensor = self._trans.new_zeros((*self.shape, 7)) + tensor[..., :4] = self._rots.get_quats() + tensor[..., 4:] = self._trans + + return tensor + + @staticmethod + def from_tensor_7( + t: torch.Tensor, + normalize_quats: bool = False, + ): + if(t.shape[-1] != 7): + raise ValueError("Incorrectly shaped input tensor") + + quats, trans = t[..., :4], t[..., 4:] + + rots = Rotation( + rot_mats=None, + quats=quats, + normalize_quats=normalize_quats + ) + + return Rigid(rots, trans) + + @staticmethod + def from_3_points( + p_neg_x_axis: torch.Tensor, + origin: torch.Tensor, + p_xy_plane: torch.Tensor, + eps: float = 1e-8 + ): + """ + Implements algorithm 21. Constructs transformations from sets of 3 + points using the Gram-Schmidt algorithm. + + Args: + p_neg_x_axis: [*, 3] coordinates + origin: [*, 3] coordinates used as frame origins + p_xy_plane: [*, 3] coordinates + eps: Small epsilon value + Returns: + A transformation object of shape [*] + """ + p_neg_x_axis = torch.unbind(p_neg_x_axis, dim=-1) + origin = torch.unbind(origin, dim=-1) + p_xy_plane = torch.unbind(p_xy_plane, dim=-1) + + e0 = [c1 - c2 for c1, c2 in zip(origin, p_neg_x_axis)] + e1 = [c1 - c2 for c1, c2 in zip(p_xy_plane, origin)] + + denom = torch.sqrt(sum((c * c for c in e0)) + eps) + e0 = [c / denom for c in e0] + dot = sum((c1 * c2 for c1, c2 in zip(e0, e1))) + e1 = [c2 - c1 * dot for c1, c2 in zip(e0, e1)] + denom = torch.sqrt(sum((c * c for c in e1)) + eps) + e1 = [c / denom for c in e1] + e2 = [ + e0[1] * e1[2] - e0[2] * e1[1], + e0[2] * e1[0] - e0[0] * e1[2], + e0[0] * e1[1] - e0[1] * e1[0], + ] + + rots = torch.stack([c for tup in zip(e0, e1, e2) for c in tup], dim=-1) + rots = rots.reshape(rots.shape[:-1] + (3, 3)) + + rot_obj = Rotation(rot_mats=rots, quats=None) + + return Rigid(rot_obj, torch.stack(origin, dim=-1)) + + def unsqueeze(self, + dim: int, + ): + """ + Analogous to torch.unsqueeze. The dimension is relative to the + shared dimensions of the rotation/translation. + + Args: + dim: A positive or negative dimension index. + Returns: + The unsqueezed transformation. + """ + if dim >= len(self.shape): + raise ValueError("Invalid dimension") + rots = self._rots.unsqueeze(dim) + trans = self._trans.unsqueeze(dim if dim >= 0 else dim - 1) + + return Rigid(rots, trans) + + @staticmethod + def cat( + ts, + dim: int, + ): + """ + Concatenates transformations along a new dimension. + + Args: + ts: + A list of T objects + dim: + The dimension along which the transformations should be + concatenated + Returns: + A concatenated transformation object + """ + rots = Rotation.cat([t._rots for t in ts], dim) + trans = torch.cat( + [t._trans for t in ts], dim=dim if dim >= 0 else dim - 1 + ) + + return Rigid(rots, trans) + + def apply_rot_fn(self, fn): + """ + Applies a Rotation -> Rotation function to the stored rotation + object. + + Args: + fn: A function of type Rotation -> Rotation + Returns: + A transformation object with a transformed rotation. + """ + return Rigid(fn(self._rots), self._trans) + + def apply_trans_fn(self, fn): + """ + Applies a Tensor -> Tensor function to the stored translation. + + Args: + fn: + A function of type Tensor -> Tensor to be applied to the + translation + Returns: + A transformation object with a transformed translation. + """ + return Rigid(self._rots, fn(self._trans)) + + def scale_translation(self, trans_scale_factor: float): + """ + Scales the translation by a constant factor. + + Args: + trans_scale_factor: + The constant factor + Returns: + A transformation object with a scaled translation. + """ + fn = lambda t: t * trans_scale_factor + return self.apply_trans_fn(fn) + + def stop_rot_gradient(self): + """ + Detaches the underlying rotation object + + Returns: + A transformation object with detached rotations + """ + fn = lambda r: r.detach() + return self.apply_rot_fn(fn) + + @staticmethod + def make_transform_from_reference(n_xyz, ca_xyz, c_xyz, eps=1e-20): + """ + Returns a transformation object from reference coordinates. + + Note that this method does not take care of symmetries. If you + provide the atom positions in the non-standard way, the N atom will + end up not at [-0.527250, 1.359329, 0.0] but instead at + [-0.527250, -1.359329, 0.0]. You need to take care of such cases in + your code. + + Args: + n_xyz: A [*, 3] tensor of nitrogen xyz coordinates. + ca_xyz: A [*, 3] tensor of carbon alpha xyz coordinates. + c_xyz: A [*, 3] tensor of carbon xyz coordinates. + Returns: + A transformation object. After applying the translation and + rotation to the reference backbone, the coordinates will + approximately equal to the input coordinates. + """ + translation = -1 * ca_xyz + n_xyz = n_xyz + translation + c_xyz = c_xyz + translation + + c_x, c_y, c_z = [c_xyz[..., i] for i in range(3)] + norm = torch.sqrt(eps + c_x ** 2 + c_y ** 2) + sin_c1 = -c_y / norm + cos_c1 = c_x / norm + zeros = sin_c1.new_zeros(sin_c1.shape) + ones = sin_c1.new_ones(sin_c1.shape) + + c1_rots = sin_c1.new_zeros((*sin_c1.shape, 3, 3)) + c1_rots[..., 0, 0] = cos_c1 + c1_rots[..., 0, 1] = -1 * sin_c1 + c1_rots[..., 1, 0] = sin_c1 + c1_rots[..., 1, 1] = cos_c1 + c1_rots[..., 2, 2] = 1 + + norm = torch.sqrt(eps + c_x ** 2 + c_y ** 2 + c_z ** 2) + sin_c2 = c_z / norm + cos_c2 = torch.sqrt(c_x ** 2 + c_y ** 2) / norm + + c2_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3)) + c2_rots[..., 0, 0] = cos_c2 + c2_rots[..., 0, 2] = sin_c2 + c2_rots[..., 1, 1] = 1 + c1_rots[..., 2, 0] = -1 * sin_c2 + c1_rots[..., 2, 2] = cos_c2 + + c_rots = rot_matmul(c2_rots, c1_rots) + n_xyz = rot_vec_mul(c_rots, n_xyz) + + _, n_y, n_z = [n_xyz[..., i] for i in range(3)] + norm = torch.sqrt(eps + n_y ** 2 + n_z ** 2) + sin_n = -n_z / norm + cos_n = n_y / norm + + n_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3)) + n_rots[..., 0, 0] = 1 + n_rots[..., 1, 1] = cos_n + n_rots[..., 1, 2] = -1 * sin_n + n_rots[..., 2, 1] = sin_n + n_rots[..., 2, 2] = cos_n + + rots = rot_matmul(n_rots, c_rots) + + rots = rots.transpose(-1, -2) + translation = -1 * translation + + rot_obj = Rotation(rot_mats=rots, quats=None) + + return Rigid(rot_obj, translation) + + def cuda(self): + """ + Moves the transformation object to GPU memory + + Returns: + A version of the transformation on GPU + """ + return Rigid(self._rots.cuda(), self._trans.cuda()) diff --git a/gafl/openfold/utils/seed.py b/gafl/openfold/utils/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..b45b81379257909e06b00839bbb90848cf3d0b3f --- /dev/null +++ b/gafl/openfold/utils/seed.py @@ -0,0 +1,19 @@ +import os +import logging +import random +import numpy as np +from pytorch_lightning.utilities.seed import seed_everything + +from openfold.utils.suppress_output import SuppressLogging + + +def seed_globally(seed=None): + if("PL_GLOBAL_SEED" not in os.environ): + if(seed is None): + seed = random.randint(0, np.iinfo(np.uint32).max) + os.environ["PL_GLOBAL_SEED"] = str(seed) + logging.info(f'os.environ["PL_GLOBAL_SEED"] set to {seed}') + + # seed_everything is a bit log-happy + with SuppressLogging(logging.INFO): + seed_everything(seed=None) diff --git a/gafl/openfold/utils/superimposition.py b/gafl/openfold/utils/superimposition.py new file mode 100644 index 0000000000000000000000000000000000000000..835498f014b8083b3f715bfb3b8dd426ce296f3e --- /dev/null +++ b/gafl/openfold/utils/superimposition.py @@ -0,0 +1,107 @@ +# Copyright 2021 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from Bio.SVDSuperimposer import SVDSuperimposer +import numpy as np +import torch + + +def _superimpose_np(reference, coords): + """ + Superimposes coordinates onto a reference by minimizing RMSD using SVD. + + Args: + reference: + [N, 3] reference array + coords: + [N, 3] array + Returns: + A tuple of [N, 3] superimposed coords and the final RMSD. + """ + sup = SVDSuperimposer() + sup.set(reference, coords) + sup.run() + return sup + +def _superimpose_single(reference, coords): + reference_np = reference.detach().cpu().numpy() + coords_np = coords.detach().cpu().numpy() + sup = _superimpose_np(reference_np, coords_np) + rot, tran = sup.get_rotran() + superimposed, rmsd = sup.get_transformed(), sup.get_rms() + return coords.new_tensor(superimposed), coords.new_tensor(rmsd), rot, tran + + +def superimpose(reference, coords, mask, return_transform=False): + """ + Superimposes coordinates onto a reference by minimizing RMSD using SVD. + + Args: + reference: + [*, N, 3] reference tensor + coords: + [*, N, 3] tensor + mask: + [*, N] tensor + Returns: + A tuple of [*, N, 3] superimposed coords and [*] final RMSDs. + """ + def select_unmasked_coords(coords, mask): + return torch.masked_select( + coords, + (mask > 0.)[..., None], + ).reshape(-1, 3) + + batch_dims = reference.shape[:-2] + flat_reference = reference.reshape((-1,) + reference.shape[-2:]) + flat_coords = coords.reshape((-1,) + reference.shape[-2:]) + flat_mask = mask.reshape((-1,) + mask.shape[-1:]) + superimposed_list = [] + rmsds = [] + rots = [] + trans = [] + for r, c, m in zip(flat_reference, flat_coords, flat_mask): + r_unmasked_coords = select_unmasked_coords(r, m) + c_unmasked_coords = select_unmasked_coords(c, m) + superimposed, rmsd, rot, tran = _superimpose_single( + r_unmasked_coords, + c_unmasked_coords + ) + rots.append(rot) + trans.append(tran) + # This is very inelegant, but idk how else to invert the masking + # procedure. + count = 0 + superimposed_full_size = torch.zeros_like(r) + for i, unmasked in enumerate(m): + if(unmasked): + superimposed_full_size[i] = superimposed[count] + count += 1 + + superimposed_list.append(superimposed_full_size) + rmsds.append(rmsd) + + superimposed_stacked = torch.stack(superimposed_list, dim=0) + rmsds_stacked = torch.stack(rmsds, dim=0) + rots_stacked = torch.tensor(np.stack(rots, axis=0), device=coords.device) + trans_stacked = torch.tensor(np.stack(trans, axis=0), device=coords.device) + + superimposed_reshaped = superimposed_stacked.reshape( + batch_dims + coords.shape[-2:] + ) + rmsds_reshaped = rmsds_stacked.reshape( + batch_dims + ) + if return_transform: + return superimposed_reshaped, rmsds_reshaped, rots_stacked, trans_stacked + return superimposed_reshaped, rmsds_reshaped diff --git a/gafl/openfold/utils/suppress_output.py b/gafl/openfold/utils/suppress_output.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c821b36a6b8d047e541a51faceef037f48ff90 --- /dev/null +++ b/gafl/openfold/utils/suppress_output.py @@ -0,0 +1,26 @@ +import logging +import sys + + +class SuppressStdout: + def __enter__(self): + self.stdout = sys.stdout + dev_null = open("/dev/null", "w") + sys.stdout = dev_null + + def __exit__(self, typ, value, traceback): + fp = sys.stdout + sys.stdout = self.stdout + fp.close() + + +class SuppressLogging: + def __init__(self, level): + self.level = level + + def __enter__(self): + logging.disable(self.level) + + def __exit__(self, typ, value, traceback): + logging.disable(logging.NOTSET) + diff --git a/gafl/openfold/utils/tensor_utils.py b/gafl/openfold/utils/tensor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5e8e4b6b5e9a26ccf1c5cedf1ff10102e75b2f --- /dev/null +++ b/gafl/openfold/utils/tensor_utils.py @@ -0,0 +1,408 @@ +# Copyright 2021 AlQuraishi Laboratory +# Copyright 2021 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial +import torch +import torch.nn as nn +from typing import Tuple, List, Callable, Any, Dict, Sequence, Optional + + +def permute_final_dims(tensor: torch.Tensor, inds: List[int]): + zero_index = -1 * len(inds) + first_inds = list(range(len(tensor.shape[:zero_index]))) + return tensor.permute(first_inds + [zero_index + i for i in inds]) + + +def flatten_final_dims(t: torch.Tensor, no_dims: int): + return t.reshape(t.shape[:-no_dims] + (-1,)) + + +def masked_mean(mask, value, dim, eps=1e-4): + mask = mask.expand(*value.shape) + return torch.sum(mask * value, dim=dim) / (eps + torch.sum(mask, dim=dim)) + + +def pts_to_distogram(pts, min_bin=2.3125, max_bin=21.6875, no_bins=64): + boundaries = torch.linspace( + min_bin, max_bin, no_bins - 1, device=pts.device + ) + dists = torch.sqrt( + torch.sum((pts.unsqueeze(-2) - pts.unsqueeze(-3)) ** 2, dim=-1) + ) + return torch.bucketize(dists, boundaries) + + +def dict_multimap(fn, dicts): + first = dicts[0] + new_dict = {} + for k, v in first.items(): + all_v = [d[k] for d in dicts] + if type(v) is dict: + new_dict[k] = dict_multimap(fn, all_v) + else: + new_dict[k] = fn(all_v) + + return new_dict + + +def one_hot(x, v_bins): + reshaped_bins = v_bins.view(((1,) * len(x.shape)) + (len(v_bins),)) + diffs = x[..., None] - reshaped_bins + am = torch.argmin(torch.abs(diffs), dim=-1) + return nn.functional.one_hot(am, num_classes=len(v_bins)).float() + + +def batched_gather(data, inds, dim=0, no_batch_dims=0): + ranges = [] + for i, s in enumerate(data.shape[:no_batch_dims]): + r = torch.arange(s) + r = r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape) - i - 1)))) + ranges.append(r) + + remaining_dims = [ + slice(None) for _ in range(len(data.shape) - no_batch_dims) + ] + remaining_dims[dim - no_batch_dims if dim >= 0 else dim] = inds + ranges.extend(remaining_dims) + return data[ranges] + + +# With tree_map, a poor man's JAX tree_map +def dict_map(fn, dic, leaf_type): + new_dict = {} + for k, v in dic.items(): + if type(v) is dict: + new_dict[k] = dict_map(fn, v, leaf_type) + else: + new_dict[k] = tree_map(fn, v, leaf_type) + + return new_dict + + +def tree_map(fn, tree, leaf_type): + if isinstance(tree, dict): + return dict_map(fn, tree, leaf_type) + elif isinstance(tree, list): + return [tree_map(fn, x, leaf_type) for x in tree] + elif isinstance(tree, tuple): + return tuple([tree_map(fn, x, leaf_type) for x in tree]) + elif isinstance(tree, leaf_type): + return fn(tree) + else: + print(type(tree)) + raise ValueError("Not supported") + + +tensor_tree_map = partial(tree_map, leaf_type=torch.Tensor) + +def _fetch_dims(tree): + shapes = [] + tree_type = type(tree) + if tree_type is dict: + for v in tree.values(): + shapes.extend(_fetch_dims(v)) + elif tree_type is list or tree_type is tuple: + for t in tree: + shapes.extend(_fetch_dims(t)) + elif tree_type is torch.Tensor: + shapes.append(tree.shape) + else: + raise ValueError("Not supported") + + return shapes + + +@torch.jit.ignore +def _flat_idx_to_idx( + flat_idx: int, + dims: Tuple[int], +) -> Tuple[int]: + idx = [] + for d in reversed(dims): + idx.append(flat_idx % d) + flat_idx = flat_idx // d + + return tuple(reversed(idx)) + + +@torch.jit.ignore +def _get_minimal_slice_set( + start: Sequence[int], + end: Sequence[int], + dims: int, + start_edges: Optional[Sequence[bool]] = None, + end_edges: Optional[Sequence[bool]] = None, +) -> Sequence[Tuple[int]]: + """ + Produces an ordered sequence of tensor slices that, when used in + sequence on a tensor with shape dims, yields tensors that contain every + leaf in the contiguous range [start, end]. Care is taken to yield a + short sequence of slices, and perhaps even the shortest possible (I'm + pretty sure it's the latter). + + end is INCLUSIVE. + """ + # start_edges and end_edges both indicate whether, starting from any given + # dimension, the start/end index is at the top/bottom edge of the + # corresponding tensor, modeled as a tree + def reduce_edge_list(l): + tally = 1 + for i in range(len(l)): + reversed_idx = -1 * (i + 1) + l[reversed_idx] *= tally + tally = l[reversed_idx] + + if(start_edges is None): + start_edges = [s == 0 for s in start] + reduce_edge_list(start_edges) + if(end_edges is None): + end_edges = [e == (d - 1) for e,d in zip(end, dims)] + reduce_edge_list(end_edges) + + # Base cases. Either start/end are empty and we're done, or the final, + # one-dimensional tensor can be simply sliced + if(len(start) == 0): + return [tuple()] + elif(len(start) == 1): + return [(slice(start[0], end[0] + 1),)] + + slices = [] + path = [] + + # Dimensions common to start and end can be selected directly + for s,e in zip(start, end): + if(s == e): + path.append(slice(s, s + 1)) + else: + break + + path = tuple(path) + divergence_idx = len(path) + + # start == end, and we're done + if(divergence_idx == len(dims)): + return [tuple(path)] + + def upper(): + sdi = start[divergence_idx] + return [ + path + (slice(sdi, sdi + 1),) + s for s in + _get_minimal_slice_set( + start[divergence_idx + 1:], + [d - 1 for d in dims[divergence_idx + 1:]], + dims[divergence_idx + 1:], + start_edges=start_edges[divergence_idx + 1:], + end_edges=[1 for _ in end_edges[divergence_idx + 1:]] + ) + ] + + def lower(): + edi = end[divergence_idx] + return [ + path + (slice(edi, edi + 1),) + s for s in + _get_minimal_slice_set( + [0 for _ in start[divergence_idx + 1:]], + end[divergence_idx + 1:], + dims[divergence_idx + 1:], + start_edges=[1 for _ in start_edges[divergence_idx + 1:]], + end_edges=end_edges[divergence_idx + 1:], + ) + ] + + # If both start and end are at the edges of the subtree rooted at + # divergence_idx, we can just select the whole subtree at once + if(start_edges[divergence_idx] and end_edges[divergence_idx]): + slices.append( + path + (slice(start[divergence_idx], end[divergence_idx] + 1),) + ) + # If just start is at the edge, we can grab almost all of the subtree, + # treating only the ragged bottom edge as an edge case + elif(start_edges[divergence_idx]): + slices.append( + path + (slice(start[divergence_idx], end[divergence_idx]),) + ) + slices.extend(lower()) + # Analogous to the previous case, but the top is ragged this time + elif(end_edges[divergence_idx]): + slices.extend(upper()) + slices.append( + path + (slice(start[divergence_idx] + 1, end[divergence_idx] + 1),) + ) + # If both sides of the range are ragged, we need to handle both sides + # separately. If there's contiguous meat in between them, we can index it + # in one big chunk + else: + slices.extend(upper()) + middle_ground = end[divergence_idx] - start[divergence_idx] + if(middle_ground > 1): + slices.append( + path + (slice(start[divergence_idx] + 1, end[divergence_idx]),) + ) + slices.extend(lower()) + + return [tuple(s) for s in slices] + + +@torch.jit.ignore +def _chunk_slice( + t: torch.Tensor, + flat_start: int, + flat_end: int, + no_batch_dims: int, +) -> torch.Tensor: + """ + Equivalent to + + t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end] + + but without the need for the initial reshape call, which can be + memory-intensive in certain situations. The only reshape operations + in this function are performed on sub-tensors that scale with + (flat_end - flat_start), the chunk size. + """ + + batch_dims = t.shape[:no_batch_dims] + start_idx = list(_flat_idx_to_idx(flat_start, batch_dims)) + # _get_minimal_slice_set is inclusive + end_idx = list(_flat_idx_to_idx(flat_end - 1, batch_dims)) + + # Get an ordered list of slices to perform + slices = _get_minimal_slice_set( + start_idx, + end_idx, + batch_dims, + ) + + sliced_tensors = [t[s] for s in slices] + + return torch.cat( + [s.view((-1,) + t.shape[no_batch_dims:]) for s in sliced_tensors] + ) + + +def chunk_layer( + layer: Callable, + inputs: Dict[str, Any], + chunk_size: int, + no_batch_dims: int, + low_mem: bool = False, +) -> Any: + """ + Implements the "chunking" procedure described in section 1.11.8. + + Layer outputs and inputs are assumed to be simple "pytrees," + consisting only of (arbitrarily nested) lists, tuples, and dicts with + torch.Tensor leaves. + + Args: + layer: + The layer to be applied chunk-wise + inputs: + A (non-nested) dictionary of keyworded inputs. All leaves must + be tensors and must share the same batch dimensions. + chunk_size: + The number of sub-batches per chunk. If multiple batch + dimensions are specified, a "sub-batch" is defined as a single + indexing of all batch dimensions simultaneously (s.t. the + number of sub-batches is the product of the batch dimensions). + no_batch_dims: + How many of the initial dimensions of each input tensor can + be considered batch dimensions. + low_mem: + Avoids flattening potentially large input tensors. Unnecessary + in most cases, and is ever so slightly slower than the default + setting. + Returns: + The reassembled output of the layer on the inputs. + """ + if not (len(inputs) > 0): + raise ValueError("Must provide at least one input") + + initial_dims = [shape[:no_batch_dims] for shape in _fetch_dims(inputs)] + orig_batch_dims = tuple([max(s) for s in zip(*initial_dims)]) + + def _prep_inputs(t): + # TODO: make this more memory efficient. This sucks + if(not low_mem): + if not sum(t.shape[:no_batch_dims]) == no_batch_dims: + t = t.expand(orig_batch_dims + t.shape[no_batch_dims:]) + t = t.reshape(-1, *t.shape[no_batch_dims:]) + else: + t = t.expand(orig_batch_dims + t.shape[no_batch_dims:]) + return t + + prepped_inputs = tensor_tree_map(_prep_inputs, inputs) + + flat_batch_dim = 1 + for d in orig_batch_dims: + flat_batch_dim *= d + + no_chunks = flat_batch_dim // chunk_size + ( + flat_batch_dim % chunk_size != 0 + ) + + i = 0 + out = None + for _ in range(no_chunks): + # Chunk the input + if(not low_mem): + select_chunk = ( + lambda t: t[i : i + chunk_size] if t.shape[0] != 1 else t + ) + else: + select_chunk = ( + partial( + _chunk_slice, + flat_start=i, + flat_end=min(flat_batch_dim, i + chunk_size), + no_batch_dims=len(orig_batch_dims) + ) + ) + + chunks = tensor_tree_map(select_chunk, prepped_inputs) + + # Run the layer on the chunk + output_chunk = layer(**chunks) + + # Allocate space for the output + if out is None: + allocate = lambda t: t.new_zeros((flat_batch_dim,) + t.shape[1:]) + out = tensor_tree_map(allocate, output_chunk) + + # Put the chunk in its pre-allocated space + out_type = type(output_chunk) + if out_type is dict: + def assign(d1, d2): + for k, v in d1.items(): + if type(v) is dict: + assign(v, d2[k]) + else: + v[i : i + chunk_size] = d2[k] + + assign(out, output_chunk) + elif out_type is tuple: + for x1, x2 in zip(out, output_chunk): + x1[i : i + chunk_size] = x2 + elif out_type is torch.Tensor: + out[i : i + chunk_size] = output_chunk + else: + raise ValueError("Not supported") + + i += chunk_size + + reshape = lambda t: t.view(orig_batch_dims + t.shape[1:]) + out = tensor_tree_map(reshape, out) + + return out diff --git a/gafl/openfold/utils/validation_metrics.py b/gafl/openfold/utils/validation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..81b8da9860452030b6e9e1c2f46b8e49fdc17b75 --- /dev/null +++ b/gafl/openfold/utils/validation_metrics.py @@ -0,0 +1,38 @@ +# Copyright 2021 AlQuraishi Laboratory +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch + + +def gdt(p1, p2, mask, cutoffs): + n = torch.sum(mask, dim=-1) + + p1 = p1.float() + p2 = p2.float() + distances = torch.sqrt(torch.sum((p1 - p2)**2, dim=-1)) + + scores = [] + for c in cutoffs: + score = torch.sum((distances <= c) * mask, dim=-1) / n + scores.append(score) + + return sum(scores) / len(scores) + + +def gdt_ts(p1, p2, mask): + return gdt(p1, p2, mask, [1., 2., 4., 8.]) + + +def gdt_ha(p1, p2, mask): + return gdt(p1, p2, mask, [0.5, 1., 2., 4.]) + diff --git a/gafl/patches/gatr_performance.patch b/gafl/patches/gatr_performance.patch new file mode 100644 index 0000000000000000000000000000000000000000..9546537d871c490235a346aae036c5aaf2dbcade --- /dev/null +++ b/gafl/patches/gatr_performance.patch @@ -0,0 +1,39 @@ +diff --git a/gatr/primitives/invariants.py b/gatr/primitives/invariants.py +index 0dc8718..70a25fc 100644 +--- a/gatr/primitives/invariants.py ++++ b/gatr/primitives/invariants.py +@@ -36,7 +36,6 @@ def compute_inner_product_mask(device=torch.device("cpu")) -> torch.Tensor: + inner_product_mask = torch.diag(gp[0]) * _compute_reversal(device=device, dtype=torch.float32) + return inner_product_mask.bool() + +- + def inner_product(x: torch.Tensor, y: torch.Tensor, channel_sum: bool = False) -> torch.Tensor: + """Computes the inner product of multivectors f(x,y) = = <~x y>_0. + +@@ -91,9 +90,8 @@ def norm(x: torch.Tensor) -> torch.Tensor: + outputs : torch.Tensor with shape (..., 1) + Geometric algebra norm of x. + """ +- +- return torch.sqrt(torch.clamp(inner_product(x, x), 0.0)) +- ++ return torch.linalg.norm(x[..., compute_inner_product_mask(device=x.device)], dim=-1, keepdim=True) # torch.linalg.norm is faster than the einsum version below ++ # return torch.sqrt(torch.clamp(inner_product(x, x), 0.0)) + + def pin_invariants(x: torch.Tensor) -> torch.Tensor: + """Computes five invariants from multivectors: scalar component, norms of the four other grades. +diff --git a/gatr/primitives/linear.py b/gatr/primitives/linear.py +index 9f7354e..d8a50df 100644 +--- a/gatr/primitives/linear.py ++++ b/gatr/primitives/linear.py +@@ -129,8 +129,8 @@ def equi_linear(x: torch.Tensor, coeffs: torch.Tensor) -> torch.Tensor: + Result. Batch dimensions are result of broadcasting between x and coeffs. + """ + basis = _compute_pin_equi_linear_basis(device=x.device, dtype=x.dtype) +- return custom_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x, path=[0, 1, 0, 1]) +- ++ # return custom_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x, path=[0, 1, 0, 1]) ++ return cached_einsum("y x a, a i j, ... x j -> ... y i", coeffs, basis, x) + + def grade_project(x: torch.Tensor) -> torch.Tensor: + """Projects an input tensor to the individual grades. diff --git a/gafl/patches/gatr_xformers.patch b/gafl/patches/gatr_xformers.patch new file mode 100644 index 0000000000000000000000000000000000000000..c802f9920ce9c7a2425e965489959e7bdea95081 --- /dev/null +++ b/gafl/patches/gatr_xformers.patch @@ -0,0 +1,64 @@ +diff --git a/gatr/primitives/attention.py b/gatr/primitives/attention.py +index bfdf495..0579a23 100644 +--- a/gatr/primitives/attention.py ++++ b/gatr/primitives/attention.py +@@ -9,7 +9,7 @@ import torch + from einops import rearrange + from torch import Tensor + from torch.nn.functional import scaled_dot_product_attention as torch_sdpa +-from xformers.ops import AttentionBias, memory_efficient_attention ++# from xformers.ops import AttentionBias, memory_efficient_attention + + from gatr.primitives.dual import join_norm + from gatr.primitives.invariants import inner_product +@@ -32,7 +32,7 @@ _TRIVECTOR_IDX = [11, 12, 13, 14] + _MASKED_OUT = float("-inf") + + # Force the use of xformers attention, even when no xformers attention mask is provided: +-FORCE_XFORMERS = False ++# FORCE_XFORMERS = False + + + def sdp_attention( +@@ -257,7 +257,7 @@ def _build_dist_vec(tri: Tensor, basis: Tensor, normalizer: Callable[[Tensor], T + Batch of 5D vectors + """ + tri_normed = tri * normalizer(tri[..., [3]]) +- vec = cached_einsum("xyz,...x,...y->...z", basis, tri_normed, tri_normed) ++ vec = cached_einsum("xyz,... x,... y->... z", basis, tri_normed, tri_normed) + return vec + + +@@ -417,7 +417,8 @@ def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, +- attn_mask: Optional[Union[AttentionBias, Tensor]] = None, ++ # attn_mask: Optional[Union[AttentionBias, Tensor]] = None, ++ attn_mask: Optional[Tensor] = None, + ) -> Tensor: + """Execute (vanilla) scaled dot-product attention. + +@@ -440,13 +441,13 @@ def scaled_dot_product_attention( + Tensor + of shape [batch, head, item, d] + """ +- if FORCE_XFORMERS or isinstance(attn_mask, AttentionBias): +- query = query.transpose(1, 2) # [batch, head, item, d] -> [batch, item, head, d] +- key = key.transpose(1, 2) +- value = value.transpose(1, 2) +- out = memory_efficient_attention( +- query.contiguous(), key.contiguous(), value, attn_bias=attn_mask +- ) +- out = out.transpose(1, 2) # [batch, item, head, d] -> [batch, head, item, d] +- return out ++ # if FORCE_XFORMERS or isinstance(attn_mask, AttentionBias): ++ # query = query.transpose(1, 2) # [batch, head, item, d] -> [batch, item, head, d] ++ # key = key.transpose(1, 2) ++ # value = value.transpose(1, 2) ++ # out = memory_efficient_attention( ++ # query.contiguous(), key.contiguous(), value, attn_bias=attn_mask ++ # ) ++ # out = out.transpose(1, 2) # [batch, item, head, d] -> [batch, head, item, d] ++ # return out + return torch_sdpa(query, key, value, attn_mask=attn_mask) diff --git a/gafl/setup.py b/gafl/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..25d9502849f3097cc35d2fc7b4c16dec3c84e37b --- /dev/null +++ b/gafl/setup.py @@ -0,0 +1,13 @@ +from setuptools import setup + +setup( + name="gafl", + packages=[ + 'gafl', + 'openfold' + ], + package_dir={ + 'gafl': './gafl', + 'openfold': './openfold', + }, +)