[
  {
    "path": ".github/workflows/python-publish.yml",
    "content": "# This workflow will upload a Python Package using Twine when a release is created\n# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries\n\n# This workflow uses actions that are not certified by GitHub.\n# They are provided by a third-party and are governed by\n# separate terms of service, privacy policy, and support\n# documentation.\n\nname: Upload Python Package\n\non:\n  release:\n    types: [published]\n\njobs:\n  deploy:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Python\n      uses: actions/setup-python@v2\n      with:\n        python-version: '3.x'\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install build\n    - name: Build package\n      run: python -m build\n    - name: Publish package\n      uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29\n      with:\n        user: __token__\n        password: ${{ secrets.PYPI_API_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Phil Wang\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "## jax2torch\n\nUse Jax functions in Pytorch with DLPack, as outlined <a href=\"https://gist.github.com/mattjj/e8b51074fed081d765d2f3ff90edf0e9\">in a gist</a> by <a href=\"https://github.com/mattjj\">@mattjj</a>. The repository was made for the purposes of making this <a href=\"https://github.com/spetti/SMURF\">differentiable alignment work</a> interoperable with Pytorch projects.\n\n## Install\n\n```bash\n$ pip install jax2torch\n```\n\n## Memory management\n\nBy default, Jax pre-allocates 90% of VRAM, which leaves Pytorch with very little left over.  To prevent this behavior, set the `XLA_PYTHON_CLIENT_PREALLOCATE` environmental variable to false before running any Jax code:\n\n```python\nimport os\nos.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n```\n\n## Usage\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1GBEEnpuCvLS1bhb_xGCO5Y40rFiQrh6G?usp=sharing) Quick test\n\n```python\nimport jax\nimport torch\nfrom jax2torch import jax2torch\nimport os\n\nos.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n\n# Jax function\n\n@jax.jit\ndef jax_pow(x, y = 2):\n  return x ** y\n\n# convert to Torch function\n\ntorch_pow = jax2torch(jax_pow)\n\n# run it on Torch data!\n\nx = torch.tensor([1., 2., 3.])\ny = torch_pow(x, y = 3)\nprint(y)  # tensor([1., 8., 27.])\n\n# And differentiate!\n\nx = torch.tensor([2., 3.], requires_grad = True)\ny = torch.sum(torch_pow(x, y = 3))\ny.backward()\nprint(x.grad) # tensor([12., 27.])\n```\n"
  },
  {
    "path": "jax2torch/__init__.py",
    "content": "from jax2torch.jax2torch import jax2torch\n"
  },
  {
    "path": "jax2torch/jax2torch.py",
    "content": "# https://gist.github.com/mattjj/e8b51074fed081d765d2f3ff90edf0e9\n\nimport torch\nfrom torch.utils import dlpack as torch_dlpack\n\nimport jax\nfrom jax import dlpack as jax_dlpack\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_map\n\nfrom inspect import signature\nfrom functools import wraps\n\ndef j2t(x_jax):\n    x_torch = torch_dlpack.from_dlpack(jax_dlpack.to_dlpack(x_jax))\n    return x_torch\n\ndef t2j(x_torch):\n    x_torch = x_torch.contiguous() # https://github.com/google/jax/issues/8082\n    x_jax = jax_dlpack.from_dlpack(torch_dlpack.to_dlpack(x_torch))\n    return x_jax\n\ndef tree_t2j(x_torch):\n    return tree_map(lambda t: t2j(t) if isinstance(t, torch.Tensor) else t, x_torch)\n\ndef tree_j2t(x_jax):\n    return tree_map(lambda t: j2t(t) if isinstance(t, jnp.ndarray) else t, x_jax)\n\ndef jax2torch(fn):\n    @wraps(fn)\n    def inner(*args, **kwargs):\n        class JaxFun(torch.autograd.Function):\n            @staticmethod\n            def forward(ctx, *args):\n                args = tree_t2j(args)\n                y_, ctx.fun_vjp = jax.vjp(fn, *args)\n                return tree_j2t(y_)\n\n            @staticmethod\n            def backward(ctx, *grad_args):\n                grad_args = tree_t2j(grad_args) if len(grad_args) > 1 else t2j(grad_args[0])\n                grads = ctx.fun_vjp(grad_args)\n                grads = tuple(map(lambda t: t if isinstance(t, jnp.ndarray) else None, grads))\n                return tree_j2t(grads)\n\n        sig = signature(fn)\n        bound = sig.bind(*args, **kwargs)\n        bound.apply_defaults()\n        return JaxFun.apply(*bound.arguments.values())\n    return inner\n"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup, find_packages\n\nsetup(\n  name = 'jax2torch',\n  packages = find_packages(exclude=[]),\n  version = '0.0.7',\n  license='MIT',\n  description = 'Jax 2 Torch',\n  author = 'Phil Wang',\n  author_email = 'lucidrains@gmail.com',\n  url = 'https://github.com/lucidrains/jax2torch',\n  keywords = [\n    'jax',\n    'pytorch'\n  ],\n  install_requires=[\n    'torch>=1.6',\n    'jax>=0.2.20'\n  ],\n  classifiers=[\n    'Development Status :: 4 - Beta',\n    'Intended Audience :: Developers',\n    'Topic :: Scientific/Engineering :: Artificial Intelligence',\n    'License :: OSI Approved :: MIT License',\n    'Programming Language :: Python :: 3.6',\n  ],\n)\n"
  }
]