{"id":14240773,"url":"https://github.com/NVIDIA/torch-harmonics","last_synced_at":"2025-08-11T16:31:51.434Z","repository":{"id":78086021,"uuid":"587447959","full_name":"NVIDIA/torch-harmonics","owner":"NVIDIA","description":"Differentiable signal processing on the sphere for PyTorch","archived":false,"fork":false,"pushed_at":"2024-10-01T16:34:18.000Z","size":9010,"stargazers_count":388,"open_issues_count":0,"forks_count":29,"subscribers_count":8,"default_branch":"main","last_synced_at":"2024-10-29T18:10:44.931Z","etag":null,"topics":["machine-learning","pytorch","signal-processing","sphere"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NVIDIA.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-10T19:21:10.000Z","updated_at":"2024-10-28T16:23:04.000Z","dependencies_parsed_at":"2023-11-13T14:28:25.611Z","dependency_job_id":"5d0ad875-d4bc-4333-89d8-f678bef4fad1","html_url":"https://github.com/NVIDIA/torch-harmonics","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Ftorch-harmonics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Ftorch-harmonics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Ftorch-harmonics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NVIDIA%2Ftorch-harmonics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NVIDIA","download_url":"https://codeload.github.com/NVIDIA/torch-harmonics/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229532163,"owners_count":18087750,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["machine-learning","pytorch","signal-processing","sphere"],"created_at":"2024-08-21T10:01:47.902Z","updated_at":"2025-08-11T16:31:50.953Z","avatar_url":"https://github.com/NVIDIA.png","language":"Jupyter Notebook","funding_links":[],"categories":["Jupyter Notebook"],"sub_categories":[],"readme":"\u003c!--\nSPDX-FileCopyrightText: Copyright (c) 2022 The torch-harmonics Authors. All rights reserved.\n\nSPDX-License-Identifier: BSD-3-Clause\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\u003e\n\n\u003c!-- \u003cdiv align=\"center\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/NVIDIA/torch-harmonics/main/images/logo/logo.png\"  width=\"568\"\u003e\n    \u003cbr\u003e\n    \u003ca href=\"https://github.com/NVIDIA/torch-harmonics/actions/workflows/tests.yml\"\u003e\u003cimg src=\"https://github.com/NVIDIA/torch-harmonics/actions/workflows/tests.yml/badge.svg\"\u003e\u003c/a\u003e\n    \u003ca href=\"https://pypi.org/project/torch_harmonics/\"\u003e\u003cimg src=\"https://img.shields.io/pypi/v/torch_harmonics\"\u003e\u003c/a\u003e\n\u003c/div\u003e --\u003e\n\n\u003c!--\n[![pypi](https://img.shields.io/pypi/v/torch_harmonics)](https://pypi.org/project/torch_harmonics/)\n--\u003e\n\n\u003c!-- # spherical harmonic transforms --\u003e\n\n# torch-harmonics\n\n[**Overview**](#overview) | [**Installation**](#installation) | [**More information**](#more-about-torch-harmonics) | [**Getting started**](#getting-started) | [**Contributors**](#contributors) | [**Cite us**](#cite-us) | [**References**](#references)\n\n[![tests](https://github.com/NVIDIA/torch-harmonics/actions/workflows/tests.yml/badge.svg)](https://github.com/NVIDIA/torch-harmonics/actions/workflows/tests.yml)\n[![pypi](https://img.shields.io/pypi/v/torch_harmonics)](https://pypi.org/project/torch_harmonics/)\n\n## Overview\n\ntorch-harmonics implements differentiable signal processing on the sphere. This includes differentiable implementations of the spherical harmonic transforms, vector spherical harmonic transforms and discrete-continuous convolutions on the sphere. The package was originally implemented to enable Spherical Fourier Neural Operators (SFNO) [1].\n\nThe SHT algorithm uses quadrature rules to compute the projection onto the associated Legendre polynomials and FFTs for the projection onto the harmonic basis. This algorithm tends to outperform others with better asymptotic scaling for most practical purposes [2].\n\ntorch-harmonics uses PyTorch primitives to implement these operations, making it fully differentiable. Moreover, the quadrature can be distributed onto multiple ranks making it spatially distributed.\n\ntorch-harmonics has been used to implement a variety of differentiable PDE solvers which generated the animations below. Moreover, it has enabled the development of Spherical Fourier Neural Operators  [1].\n\n\u003cdiv align=\"center\"\u003e\n\u003ctable border=\"0\" cellspacing=\"0\" cellpadding=\"0\"\u003e\n    \u003ctr\u003e\n        \u003ctd\u003e\u003cimg src=\"https://media.githubusercontent.com/media/NVIDIA/torch-harmonics/main/images/sfno.gif\"  width=\"240\"\u003e\u003c/td\u003e\n        \u003ctd\u003e\u003cimg src=\"https://media.githubusercontent.com/media/NVIDIA/torch-harmonics/main/images/zonal_jet.gif\"  width=\"240\"\u003e\u003c/td\u003e\n        \u003ctd\u003e\u003cimg src=\"https://media.githubusercontent.com/media/NVIDIA/torch-harmonics/main/images/allen-cahn.gif\"  width=\"240\"\u003e\u003c/td\u003e\n    \u003c/tr\u003e\n\u003c!--     \u003ctr\u003e\n        \u003ctd style=\"text-align:center; border-style : hidden!important;\"\u003eShallow Water Eqns.\u003c/td\u003e\n        \u003ctd style=\"text-align:center; border-style : hidden!important;\"\u003eGinzburg-Landau Eqn.\u003c/td\u003e\n        \u003ctd style=\"text-align:center; border-style : hidden!important;\"\u003eAllen-Cahn Eqn.\u003c/td\u003e\n    \u003c/tr\u003e  --\u003e\n\u003c/table\u003e\n\u003c/div\u003e\n\n\n## Installation\nA simple installation can be directly done from PyPI:\n\n```bash\npip install torch-harmonics\n```\nIf you are planning to use spherical convolutions, we recommend building the corresponding custom CUDA kernels. To enforce this, you can set the `FORCE_CUDA_EXTENSION` flag. You may also want to set appropriate architectures with the `TORCH_CUDA_ARCH_LIST` flag. Finally, make sure to disable build isolation via the `--no-build-isolation` flag to ensure that the custom kernels are built with the existing torch installation.\n```bash\nexport FORCE_CUDA_EXTENSION=1\nexport TORCH_CUDA_ARCH_LIST=\"7.0 7.2 7.5 8.0 8.6 8.7 9.0+PTX\"\npip install --no-build-isolation torch-harmonics\n```\n:warning: Please note that the custom CUDA extensions currently only support CUDA architectures \u003e= 7.0.\n\nIf you want to actively develop torch-harmonics, we recommend building it in your environment from github:\n\n```bash\ngit clone git@github.com:NVIDIA/torch-harmonics.git\ncd torch-harmonics\npip install -e .\n```\n\nAlternatively, use the Dockerfile to build your custom container after cloning:\n\n```bash\ngit clone git@github.com:NVIDIA/torch-harmonics.git\ncd torch-harmonics\ndocker build . -t torch_harmonics\ndocker run --gpus all -it --rm --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 torch_harmonics\n```\n\n## More about torch-harmonics\n\n### Spherical harmonics\n\nThe [spherical harmonics](https://en.wikipedia.org/wiki/Spherical_harmonics) are special functions defined on the two-dimensional sphere $S^2$ (embedded in three dimensions). They form an orthonormal basis of the space of square-integrable functions defined on the sphere $L^2(S^2)$ and are comparable to the harmonic functions defined on a circle/torus. The spherical harmonics are defined as\n\n$$\nY_l^m(\\theta, \\lambda) = \\sqrt{\\frac{(2l + 1)}{4 \\pi} \\frac{(l - m)!}{(l + m)!}} P_l^m(\\cos \\theta)  \\exp(im\\lambda),\n$$\n\nwhere $\\theta$ and $\\lambda$ are colatitude and longitude respectively, and $P_l^m$ the normalized, [associated Legendre polynomials](https://en.wikipedia.org/wiki/Associated_Legendre_polynomials).\n\n\u003cdiv align=\"center\"\u003e\n\u003cimg src=\"https://media.githubusercontent.com/media/NVIDIA/torch-harmonics/main/images/spherical_harmonics.gif\" width=\"432\"\u003e\n\u003cbr\u003e\nSpherical harmonics up to degree 5\n\u003c/div\u003e\n\n### Spherical harmonic transform\n\nThe spherical harmonic transform (SHT)\n\n$$\nf_l^m = \\int_{S^2}  \\overline{Y_{l}^{m}}(\\theta, \\lambda) f(\\theta, \\lambda) \\mathrm{d} \\mu(\\theta, \\lambda)\n$$\n\nrealizes the projection of a signal $f(\\theta, \\lambda)$ on $S^2$ onto the spherical harmonics basis. The SHT generalizes the Fourier transform on the sphere. Conversely, a truncated series expansion of a function $f$ can be written in terms of spherical harmonics as\n\n$$\nf (\\theta, \\lambda) = \\sum_{m=-M}^{M} \\exp(im\\lambda) \\sum_{l=|m|}^{M} \\hat f_l^m  P_l^m (\\cos \\theta),\n$$\n\nwhere $\\hat{f}_l^m$, are the expansion coefficients associated to the mode $m$, $n$.\n\nThe implementation of the SHT follows the algorithm as presented in [2]. A direct spherical harmonic transform can be accomplished by a Fourier transform\n\n$$\n\\hat f^m(\\theta) = \\frac{1}{2 \\pi} \\int_{0}^{2\\pi} f(\\theta, \\lambda) \\exp(-im\\lambda) \\mathrm{d} \\lambda\n$$\n\nin longitude and a Legendre transform\n\n$$\n\\hat f_l^m = \\frac{1}{2} \\int^{\\pi}_0 \\hat f^{m} (\\theta) P_l^m (\\cos \\theta) \\sin \\theta \\mathrm{d} \\theta\n$$\n\nin latitude.\n\n### Discrete Legendre transform\n\nThe second integral, which computed the projection onto the Legendre polynomials is realized with quadrature. On the Gaussian grid, we use Gaussian quadrature in the $\\cos \\theta$ domain. The integral\n\n$$\n\\hat f_l^m = \\frac{1}{2} \\int_{-1}^1 \\hat{f}^m(\\arccos x) P_l^m (x) \\mathrm{d} x\n$$\n\nis obtained with the substitution $x = \\cos \\theta$ and then approximated by the sum\n\n$$\n\\hat f_l^m = \\sum_{j=1}^{N_\\theta}  \\hat{f}^m(\\arccos x_j) P_l^m(x_j) w_j.\n$$\n\nHere, $x_j \\in [-1,1]$ are the quadrature nodes with the respective quadrature weights $w_j$.\n\n### Discrete-continuous convolutions on the sphere\n\ntorch-harmonics now provides local discrete-continuous (DISCO) convolutions as outlined in [5] on the sphere. These are use in local neural operators [2] to generalize convolutions to structured and unstructured meshes on the sphere.\n\n### Spherical (neighborhood) attention\n\ntorch-harmonics introducers spherical attention mechanisms which correctly generalize the attention mechanism to the sphere. The use of quadrature rules makes the resulting operations approximately equivariant and equivariant in the continuous limit. Moreover, neighborhood attention is correctly generalized onto the sphere by using the geodesic distance to determine the size of the neighborhood.\n\n## Getting started\n\nThe main functionality of `torch_harmonics` is provided in the form of `torch.nn.Modules` for composability. A minimum example is given by:\n\n```python\nimport torch\nimport torch_harmonics as th\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nnlat = 512\nnlon = 2*nlat\nbatch_size = 32\nsignal = torch.randn(batch_size, nlat, nlon, device=device)\n\n# transform data on an equiangular grid\nsht = th.RealSHT(nlat, nlon, grid=\"equiangular\").to(device)\n\ncoeffs = sht(signal)\n```\n\nTo enable scalable model-parallelism, `torch-harmonics` implements a distributed variant of the SHT located in `torch_harmonics.distributed`.\n\nDetailed usage of torch-harmonics, alongside helpful analysis provided in a series of notebooks:\n\n1. [Getting started](./notebooks/getting_started.ipynb)\n2. [Quadrature](./notebooks/quadrature.ipynb)\n3. [Visualizing the spherical harmonics](./notebooks/plot_spherical_harmonics.ipynb)\n4. [Spectral fitting vs. SHT](./notebooks/gradient_analysis.ipynb)\n5. [Conditioning of the Gramian](./notebooks/conditioning_sht.ipynb)\n6. [Solving the Helmholtz equation](./notebooks/helmholtz.ipynb)\n7. [Solving the shallow water equations](./notebooks/shallow_water_equations.ipynb)\n8. [Training Spherical Fourier Neural Operators (SFNO)](./notebooks/train_sfno.ipynb)\n9. [Resampling signals on the sphere](./notebooks/resample_sphere.ipynb)\n\n## Examples and reproducibility\n\nThe `examples` folder contains training scripts for three distinct tasks:\n\n* [solution of the shallow water equations on the rotating sphere](./examples/shallow_water_equations/train.py)\n* [depth estimation on the sphere](./examples/depth/train.py)\n* [semantic segmentation on the sphere](./examples/segmentation/train.py)\n\nResults from the papers can generally be reproduced by running `python train.py`. In the case of some older results the number of epochs and learning-rate may need to be adjusted by passing the corresponding command line argument.\n\n## Remarks on automatic mixed precision (AMP) support\n\nNote that torch-harmonics uses Fourier transforms from `torch.fft` which in turn uses kernels from the optimized `cuFFT` library. This library supports fourier transforms of `float32` and `float64` (i.e. `single` and `double` precision) tensors for all input sizes. For `float16` (i.e. `half` precision) and `bfloat16` inputs however, the dimensions which are transformed are restricted to powers of two. Since data is converted to one of these reduced precision floating point formats when `torch.autocast` is used, torch-harmonics will issue an error when the input shapes are not powers of two. For these cases, we recommend disabling autocast for the harmonics transform specifically:\n\n```python\nimport torch\nimport torch_harmonics as th\n\nsht = th.RealSHT(512, 1024, grid=\"equiangular\").cuda()\n\nwith torch.autocast(device_type=\"cuda\", enabled = True):\n   # do some AMP converted math here\n   x = some_math(x)\n   # convert tensor to float32\n   x = x.to(torch.float32)\n   # now disable autocast specifically for the transform,\n   # making sure that the tensors are not converted\n   # back to reduced precision internally\n   with torch.autocast(device_type=\"cuda\", enabled = False):\n      xt = sht(x)\n\n   # continue operating on the transformed tensor\n   xt = some_more_math(xt)\n```\n\nDepending on the problem, it might be beneficial to upcast data to `float64` instead of `float32` precision for numerical stability.\n\n## Contributors\n\n[Boris Bonev](https://bonevbs.github.io) (bbonev@nvidia.com), [Thorsten Kurth](https://github.com/azrael417) (tkurth@nvidia.com), [Max Rietmann](https://github.com/rietmann-nv), [Mauro Bisson](https://scholar.google.com/citations?hl=en\u0026user=f0JE-0gAAAAJ), [Andrea Paris](https://github.com/apaaris), [Alberto Carpentieri](https://github.com/albertocarpentieri), [Massimiliano Fatica](https://scholar.google.com/citations?user=Deaq4uUAAAAJ\u0026hl=en), [Nikola Kovachki](https://kovachki.github.io), [Jean Kossaifi](http://jeankossaifi.com), [Christian Hundt](https://github.com/gravitino)\n\n## Cite us\n\nIf you use `torch-harmonics` in an academic paper, please cite [1]\n\n```bibtex\n@misc{bonev2023spherical,\n      title={Spherical Fourier Neural Operators: Learning Stable Dynamics on the Sphere},\n      author={Boris Bonev and Thorsten Kurth and Christian Hundt and Jaideep Pathak and Maximilian Baust and Karthik Kashinath and Anima Anandkumar},\n      year={2023},\n      eprint={2306.03838},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG}\n}\n```\n\n## References\n\n\u003ca id=\"1\"\u003e[1]\u003c/a\u003e\nBonev B., Kurth T., Hundt C., Pathak, J., Baust M., Kashinath K., Anandkumar A.;\nSpherical Fourier Neural Operators: Learning Stable Dynamics on the Sphere;\nInternational Conference on Machine Learning, 2023. [arxiv link](https://arxiv.org/abs/2306.03838)\n\n\u003ca id=\"1\"\u003e[2]\u003c/a\u003e\nLiu-Schiaffini M., Berner J., Bonev B., Kurth T., Azizzadenesheli K., Anandkumar A.;\nNeural Operators with Localized Integral and Differential Kernels;\nInternational Conference on Machine Learning, 2024. [arxiv link](https://arxiv.org/abs/2402.16845)\n\n\u003ca id=\"1\"\u003e[3]\u003c/a\u003e\nSchaeffer N.;\nEfficient spherical harmonic transforms aimed at pseudospectral numerical simulations;\nG3: Geochemistry, Geophysics, Geosystems, 2013.\n\n\u003ca id=\"1\"\u003e[4]\u003c/a\u003e\nWang B., Wang L., Xie Z.;\nAccurate calculation of spherical and vector spherical harmonic expansions via spectral element grids;\nAdv Comput Math, 2018.\n\n\u003ca id=\"1\"\u003e[5]\u003c/a\u003e\nOcampo, Price, McEwen, Scalable and equivariant spherical CNNs by discrete-continuous (DISCO) convolutions, ICLR (2023), arXiv:2209.13603\n\n\u003ca id=\"1\"\u003e[6]\u003c/a\u003e\nBonev B., Rietmann M., Paris A., Carpentieri A., Kurth T.; Attention on the Sphere; [arxiv link](https://arxiv.org/abs/2505.11157)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNVIDIA%2Ftorch-harmonics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FNVIDIA%2Ftorch-harmonics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNVIDIA%2Ftorch-harmonics/lists"}