├── .gitignore ├── pyproject.toml ├── test_fwdlap.py ├── README.md ├── LICENSE └── fwdlap.py /.gitignore: -------------------------------------------------------------------------------- 1 | # User defined 2 | *~ 3 | checkpoint* 4 | model.ckpt.* 5 | .vscode 6 | .ipynb_* 7 | *.swp 8 | 9 | # Byte-compiled / optimized / DLL files 10 | __pycache__/ 11 | *.py[cod] 12 | *$py.class 13 | 14 | # C extensions 15 | *.so 16 | 17 | # Distribution / packaging 18 | .Python 19 | build/ 20 | develop-eggs/ 21 | dist/ 22 | downloads/ 23 | eggs/ 24 | .eggs/ 25 | lib/ 26 | lib64/ 27 | parts/ 28 | sdist/ 29 | var/ 30 | wheels/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | _version.py 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Environments 49 | .env 50 | .venv 51 | env/ 52 | venv/ 53 | ENV/ 54 | env.bak/ 55 | venv.bak/ -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=60", 4 | "setuptools-scm>=8.0" 5 | ] 6 | build-backend = "setuptools.build_meta" 7 | 8 | 9 | [project] 10 | name = "fwdlap" 11 | description = "Forward Laplacian implementation with JAX tracer" 12 | authors = [{name = "Yixiao Chen", email = "yixiaoc@princeton.edu"}] 13 | license = {text = "Apache-2.0"} 14 | requires-python = ">=3.9" 15 | classifiers = [ 16 | "Development Status :: 3 - Alpha" 17 | ] 18 | readme = "README.md" 19 | dynamic = ["version"] 20 | dependencies = [ 21 | "jax >= 0.4.36", 22 | ] 23 | 24 | [project.urls] 25 | Homepage = "https://github.com/y1xiaoc/fwdlap" 26 | 27 | [project.optional-dependencies] 28 | test = ["pytest"] 29 | 30 | 31 | [tool.setuptools] 32 | py-modules = ["fwdlap"] 33 | 34 | [tool.setuptools_scm] 35 | 36 | 37 | [tool.ruff] 38 | select =[ 39 | "E", # pycodestyle error 40 | "F", # pyflake 41 | "W", # whitespace 42 | "NPY", # numpy 43 | "TID", # tidy-imports 44 | "B", # bugbear 45 | ] 46 | ignore = [ 47 | "E721", # Do not compare types, use 'isinstance()' 48 | "E731", # Do not assign a lambda expression, use a def 49 | "E741", # Don't use I, O, l as variable names 50 | "F401", # unused import 51 | "B011", # Do not assert False 52 | ] 53 | line-length = 100 54 | target-version = "py39" # Minimum jax version 55 | 56 | [tool.ruff.per-file-ignores] 57 | "__init__.py" = ["E402"] 58 | -------------------------------------------------------------------------------- /test_fwdlap.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Yixiao Chen. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # The stax network is adapted from readme in jax repo 16 | 17 | from functools import partial 18 | 19 | import pytest 20 | import numpy as np 21 | 22 | import jax 23 | import jax.numpy as jnp 24 | from jax.example_libraries import stax 25 | from jax.example_libraries.stax import ( 26 | Conv, Dense, MaxPool, Relu, Flatten, Softplus) 27 | 28 | import fwdlap 29 | 30 | 31 | def get_network(): 32 | # Use stax to set up network initialization and evaluation functions 33 | net_init, net_apply = stax.serial( 34 | Conv(32, (3, 3), padding='SAME'), Relu, 35 | Conv(64, (3, 3), padding='SAME'), Relu, 36 | MaxPool((2, 2)), Flatten, 37 | Dense(128), Relu, 38 | Dense(10), Softplus, 39 | ) 40 | # Initialize parameters, no batch shape 41 | rng = jax.random.PRNGKey(0) 42 | in_shape = (1, 5, 5, 2) 43 | out_shape, net_params = net_init(rng, in_shape) 44 | return net_apply, net_params, in_shape, out_shape 45 | 46 | 47 | @pytest.fixture(scope="module") 48 | def common_data(): 49 | key = jax.random.PRNGKey(1) 50 | net_apply, net_params, in_shape, out_shape = get_network() 51 | net_fn = jax.jit(partial(net_apply, net_params)) # mysterious error if no jit 52 | x = jax.random.normal(key, in_shape) 53 | jac = jax.jacfwd(net_fn)(x) 54 | hess = jax.hessian(net_fn)(x) 55 | lap = hess.reshape(*out_shape, x.size, x.size).trace(0, -1, -2) 56 | return net_fn, x, jac, lap 57 | 58 | 59 | @pytest.mark.parametrize("symbolic_zero", [True, False]) 60 | @pytest.mark.parametrize("use_jit", [True, False]) 61 | def test_lap(common_data, symbolic_zero, use_jit): 62 | net_fn, x, jac_target, lap_target = common_data 63 | eye = jnp.eye(x.size).reshape(x.size, *x.shape) 64 | zero = (fwdlap.zero_tangent_from_primal(x) 65 | if symbolic_zero else jnp.zeros_like(x)) 66 | flap_fn = (jax.jit(partial(fwdlap.lap, net_fn)) 67 | if use_jit else partial(fwdlap.lap, net_fn)) 68 | out, jac, lap = flap_fn((x,), (eye,), (zero,)) 69 | jac = jnp.moveaxis(jac, -1, 0).reshape(*out.shape, *x.shape) 70 | np.testing.assert_allclose(out, net_fn(x), atol=1e-5) 71 | np.testing.assert_allclose(jac, jac_target, atol=1e-5) 72 | np.testing.assert_allclose(lap, lap_target, atol=1e-5) 73 | 74 | 75 | @pytest.mark.parametrize("symbolic_zero", [True, False]) 76 | @pytest.mark.parametrize("use_jit", [True, False]) 77 | def test_lap_partial(common_data, symbolic_zero, use_jit): 78 | net_fn, x, jac_target, lap_target = common_data 79 | eye = jnp.eye(x.size).reshape(x.size, *x.shape) 80 | zero = (fwdlap.zero_tangent_from_primal(x) 81 | if symbolic_zero else jnp.zeros_like(x)) 82 | out, lap_pe = fwdlap.lap_partial(net_fn, (x,), (eye,), (zero,)) 83 | lap_fn = jax.jit(lap_pe) if use_jit else lap_pe 84 | jac, lap = lap_fn((eye,), (zero,)) 85 | jac = jnp.moveaxis(jac, -1, 0).reshape(*out.shape, *x.shape) 86 | np.testing.assert_allclose(out, net_fn(x), atol=1e-5) 87 | np.testing.assert_allclose(jac, jac_target, atol=1e-5) 88 | np.testing.assert_allclose(lap, lap_target, atol=1e-5) 89 | 90 | 91 | @pytest.mark.parametrize("symbolic_zero", [True, False]) 92 | @pytest.mark.parametrize("use_jit", [True, False]) 93 | def test_lap_vmapped(common_data, symbolic_zero, use_jit): 94 | net_fn, x, _, lap_target = common_data 95 | vnet_fn = jax.vmap(net_fn, in_axes=0, out_axes=0) 96 | x = jnp.stack([x, x]) 97 | lap_target = jnp.stack([lap_target, lap_target]) 98 | eye = jnp.eye(x.size).reshape(x.size, *x.shape) 99 | zero = (fwdlap.zero_tangent_from_primal(x) 100 | if symbolic_zero else jnp.zeros_like(x)) 101 | flap_fn = (jax.jit(partial(fwdlap.lap, vnet_fn)) 102 | if use_jit else partial(fwdlap.lap, vnet_fn)) 103 | _, _, lap = flap_fn((x,), (eye,), (zero,)) 104 | np.testing.assert_allclose(lap, lap_target, atol=1e-5) 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Poor Man's Forward Laplacian (using JAX Tracer!) 2 | 3 | This is a fan implemented (unofficial) version of the method of computing laplacian in one single forward pass, as described in the brilliant paper [Forward Laplacian: A New Computational Framework for 4 | Neural Network-based Variational Monte Carlo](https://arxiv.org/pdf/2307.08214.pdf). 5 | 6 | ## Installation 7 | 8 | Everything of the implementation is in this single file [`fwdlap.py`](./fwdlap.py). Feel free to copy it to the place you need. 9 | 10 | Alternatively, use pip to install it: 11 | ```bash 12 | pip install git+https://github.com/y1xiaoc/fwdlap 13 | ``` 14 | Or clone the repo and install it locally with `pip install -e .` if you need editable mode. 15 | 16 | ## Usage 17 | 18 | The module provides two functions for forward laplacian calculation: `lap` and `lap_partial`. They are the laplacian version of `jax.jvp` and `jax.linearize` respectively. The usage of the two functions are very similar to their counterpart, but this time the tangent vector need to be batched and an extra input argument of laplacian is needed. 19 | 20 | For directly calculating the primal output, jacobian and laplacian, use 21 | ```python 22 | primals_out, jacobians_out, laplacians_out = fwdlap.lap(fun, primals_in, jacobians_in, laplaicians_in) 23 | ``` 24 | Note the inputs of `fun` does not support nested pytrees. They have to be "flattened" so that primals_in is a tuple or list of arrays (or scalars). 25 | 26 | For the partial eval version, use 27 | ```python 28 | primals_out, lap_pe = fwdlap.lap_partial(fun, primals_in, example_jacobians_in, example_laplaicians_in) 29 | ``` 30 | Only the shapes of `example_jacobians_in` and `example_laplaicians_in` matter. After this, call `lap_pe` with the actual `jacobians_in` and `laplaicians_in` to get the actual output. 31 | ```python 32 | jacobians_out, laplacians_out = lap_pe(jacobians_in, laplaicians_in) 33 | ``` 34 | 35 | Please check the [docstrings](./fwdlap.py#L42) of these two functions for more details. The [test](./test_fwdlap.py#L65) file also contains some examples of usage, including passing symbolic zeros. 36 | 37 | ## Why this implementation? 38 | 39 | The method proposed in the Forward Laplacian paper is in fact very similar to the existing (yet experimental) module [`jet`](https://jax.readthedocs.io/en/latest/jax.experimental.jet.html) in jax, up to the second order. The propagation rules are almost identical, with only one difference that in forward laplacian, the jacobian contribution to the laplacian (first term in eq. 17 of the paper) is summed over for every operation, while in jet it is simply `vmap`'ed and summed at end of the pass. (See [this discussion](https://github.com/google/jax/discussions/9598) for how to use jet to calculate laplacian.) This difference makes forward laplacian consume less memory comparing to `vmap`'ed jet, and may save some computation time as well (at a cost of doing a reduced sum for every operation). 40 | 41 | Given the similarity of the two methods, I tried to implement the forward laplacian method using jax tracer, taking reference on the `jet` module. However, the implementation of `jet` is very inefficient, because it will always instantiate all the symbolic zeros. Therefore, I wrote my own tracer without using any jet rules, but simply `jvp` twice for 2nd order derivatives and make all `Zero`s pass through. The result is this module, [`fwdlap.py`](./fwdlap.py)! 42 | 43 | Comparing to the proposed implementation in the paper, which overloads all `jax.numpy` operators, this implementation works on the jax primitive level, reusing all the jvp rules and let jax compiler do the trick. This approach is much cheaper in terms of coding cost, and that's why I call it _"poor man's"_ version. In addition, it is also more flexible, as it can in principle handle any jax function, not limited to the operators overloaded in `jax.numpy`. The drawback is I did not spend much time on optimizing the forward rule for each operator. However, thanks to the powerful compiler of jax (and my careful treatment of symbolic zeros), most of these optimization are not necessary (such as those for linear or element-wise operators). The bilinear operators are the only exceptions, for which I implemented a special rule in the tracer to take advantage of the symmetry of the Hessian matrix. 44 | 45 | At the time of writing, the performance comparison with the official version is not available, as the official one has not been released yet and I have no access to it. 46 | 47 | ## Example on kinetic energy 48 | 49 | Here's an example of using the `fwdlap` module to calculate the kinetic energy of a given log of wavefunction `log_psi`. It supports (mini_batched) loop evaluation in both the batch dimension (`batch_size`) and the inner jacobian dimension (`inner_size`). Set them to `None` will use the full batch version. Choosing these two parameters carefully, this implementation can achieve 3x speed up on some attention based neural network wavefunctions, comparing to the old one used in the ferminet repo. It also saves memory as there's no need to store the intermediate results of backward propagation. 50 | 51 | ```python 52 | import jax 53 | from jax import lax 54 | from jax import numpy as jnp 55 | 56 | import fwdlap 57 | 58 | def calc_ke_fwdlap(log_psi, x, inner_size=None, batch_size=None): 59 | # calc -0.5 * (\nable^2 \psi) / \psi 60 | # handle batch of x automatically 61 | def _lapl_over_psi(x): 62 | # (\nable^2 f) / f = \nabla^2 log|f| + (\nabla log|f|)^2 63 | # x is assumed to have shape [n_ele, n_dim], not batched 64 | x_shape = x.shape 65 | flat_x = x.reshape(-1) 66 | ncoord = flat_x.size 67 | f = lambda flat_x: log_psi(flat_x.reshape(x_shape)) # take flattened x 68 | eye = jnp.eye(ncoord, dtype=x.dtype) 69 | zero = fwdlap.zero_tangent_from_primal(flat_x) 70 | if inner_size is None: 71 | primals, grads, laps = fwdlap.lap(f, (flat_x,), (eye,), (zero,)) 72 | laplacian = (grads**2).sum() + laps 73 | else: 74 | eye = eye.reshape(ncoord//inner_size, inner_size, ncoord) 75 | primals, f_lap_pe = fwdlap.lap_partial(f, (flat_x,), (eye[0],), (zero,)) 76 | def loop_fn(i, val): 77 | (jac, lap) = f_lap_pe((eye[i],), (zero,)) 78 | val += (jac**2).sum() + lap 79 | return val 80 | laplacian = lax.fori_loop(0, ncoord//inner_size, loop_fn, 0.0) 81 | return laplacian 82 | # handle batch of x, assuming x has at most 3 dims 83 | if x.ndim <= 2: 84 | return -0.5 * _lapl_over_psi(x) 85 | if x.ndim != 3: 86 | msg = f"only support x with ndim less than 3, get {x.ndim}" 87 | raise ValueError(msg) 88 | # batched version when x.ndim == 3 89 | lapl_fn = jax.vmap(_lapl_over_psi) 90 | if batch_size is None: 91 | return -0.5 * lapl_fn(x) 92 | x_batched = x.reshape(x.shape[0]//batch_size, batch_size, *x.shape[1:]) 93 | return -0.5 * lax.map(lapl_fn, x_batched).reshape(-1) 94 | ``` 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /fwdlap.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Yixiao Chen. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # This code takes references from jet and jvp in jax 16 | 17 | from typing import Any, Callable 18 | 19 | from functools import partial 20 | 21 | import jax 22 | from jax import lax 23 | import jax.numpy as jnp 24 | from jax.tree_util import (tree_structure, treedef_is_leaf, 25 | tree_flatten, tree_unflatten, Partial) 26 | 27 | from jax import core 28 | from jax.extend import core as ext_core 29 | try: 30 | from jax.extend import linear_util as lu 31 | except ImportError: 32 | from jax import linear_util as lu 33 | from jax.api_util import flatten_fun_nokwargs, shaped_abstractify, debug_info 34 | from jax.interpreters import ad 35 | from jax.interpreters import partial_eval as pe 36 | from jax.interpreters.ad import Zero, instantiate_zeros 37 | from jax.dtypes import float0 38 | 39 | from jax._src.util import split_list, unzip3, weakref_lru_cache, safe_map as smap 40 | 41 | try: 42 | from jax.experimental.pjit import pjit_p as jit_p 43 | except ImportError: 44 | jit_p = ext_core.primitives.jit_p 45 | 46 | 47 | def lap(fun, primals, jacobians, laplacians): 48 | """ 49 | Computes the (forward mode) jacobian and laplacian of a function `fun`. 50 | 51 | This function has very similar semantics to `jax.jvp`, except that it 52 | requires batched tangent vectors (jacobians) and laplacians for each input, 53 | and returns batched jvp and the cumulated laplacian from the batched tangents. 54 | 55 | Args: 56 | fun: A function that takes in `primals` and returns an output. 57 | Its arguments have to be arrays or scalars, but not in nested python 58 | containers. Its output can be any pytrees of arrays or scalars. 59 | primals: The primal values at which the jacobian of `fun` should be 60 | evaluated. Should be either a tuple or a list of arguments. and its 61 | length should be equal to the number of positional parameters of `fun`. 62 | jacobians: The jacobian matrices (batched tangent vectors) for each 63 | input to evaluate the jvp. Should be either a tuple or a list of 64 | arguments with the same tree structure as `primals`, with an exception 65 | of symbolic `Zero` values that represent zero jacobians. The jacobians 66 | should have an extra leading dimension compared to the primal values, 67 | which is the batch size and will be summed over in the laplacian. 68 | laplacians: The laplacian vectors for each input to evaluate the 69 | forward laplacian. Should be either a tuple or a list of arguments 70 | with the same tree structure as `primals`, with an exception of 71 | symbolic `Zero` values that represent zero laplacians. 72 | 73 | Returns: 74 | A tuple of three elements: 75 | - The outputs of `fun` at `primals`. 76 | - Jacobian matrices with respect to each output. 77 | - Laplacian vectors with respect to each output. 78 | """ 79 | check_no_nested(primals, jacobians, laplacians) 80 | jsize = get_jsize(jacobians) 81 | f, out_tree = flatten_fun_output( 82 | lu.wrap_init(fun, debug_info=debug_info("lap", fun, primals, {}))) 83 | out_primals, out_jacs, out_laps = lap_fun( 84 | lap_subtrace(f), jsize, True).call_wrapped( 85 | primals, jacobians, laplacians) 86 | return (tree_unflatten(out_tree(), out_primals), 87 | tree_unflatten(out_tree(), out_jacs), 88 | tree_unflatten(out_tree(), out_laps)) 89 | 90 | 91 | def lap_partial(fun, primals, example_jacs, example_laps): 92 | """ 93 | The partial eval version of `lap`. 94 | 95 | This function will compute the primal output of `fun` and postpone 96 | the jacobian and laplacian calculation in a returned function. 97 | It takes exact same arguments as `lap`, but this time `example_jacs` 98 | and `example_laps` are only used to determine the shape. 99 | 100 | Args: 101 | fun: A function that takes in `primals` and returns an output. 102 | Its arguments have to be arrays or scalars, but not in nested python 103 | containers. Its output can be any pytrees of arrays or scalars. 104 | primals: The primal values at which the jacobian of `fun` should be 105 | evaluated. Should be either a tuple or a list of arguments. and its 106 | length should be equal to the number of positional parameters of `fun`. 107 | example_jacs: The jacobian matrices (batched tangent vectors) for each 108 | input to evaluate the jvp. See `lap` for more details. The value does 109 | not matter, only the shape (or whether it's symboilc `Zero`) is used. 110 | example_laps: The laplacian vectors for each input to evaluate the 111 | forward laplacian. See `lap` for more details. Only the shape 112 | (or whether it's symboilc `Zero`) is used. 113 | 114 | Returns: 115 | A tuple of two elements: 116 | - The output of `fun` at `primals`. 117 | - A function that takes in the jacobian and laplacian arguments 118 | and returns the jacobian and laplacian of the output. The tree 119 | structure of jacobian and laplatian arguments should be the same 120 | as `example_jacs` and `example_laps` respectively. 121 | """ 122 | # make the lap tracer with wrapped (flattened) function 123 | check_no_nested(primals, example_jacs, example_laps) 124 | jsize = get_jsize(example_jacs) 125 | f, f_out_tree = flatten_fun_output( 126 | lu.wrap_init(fun, debug_info=debug_info("lap_partial", fun, primals, {}))) 127 | f_lap = lap_fun(lap_subtrace(f), jsize, True) 128 | # partial eval, including pre and post process 129 | in_pvals = (tuple(pe.PartialVal.known(p) for p in primals) 130 | + tuple(pe.PartialVal.unknown(core.get_aval(p)) 131 | for p in tree_flatten((example_jacs, example_laps))[0])) 132 | _, in_tree = tree_flatten((primals, example_jacs, example_laps)) 133 | f_lap_flat, lap_out_tree = flatten_fun_nokwargs(f_lap, in_tree) 134 | jaxpr, out_pvals, consts = pe.trace_to_jaxpr_nounits(f_lap_flat, in_pvals) 135 | op_pvals, oj_pvals, ol_pvals = tree_unflatten(lap_out_tree(), out_pvals) 136 | # collect known primals out 137 | f_out_tree = f_out_tree() 138 | assert all(opp.is_known() for opp in op_pvals) 139 | op_flat = [opp.get_known() for opp in op_pvals] 140 | primals_out = tree_unflatten(f_out_tree, op_flat) 141 | # build function for unknown laplacian 142 | def lap_pe(consts, jacs, laps): 143 | oj_ol_flat = core.eval_jaxpr(jaxpr, consts, *tree_flatten((jacs, laps))[0]) 144 | oj_ol_flat_ = iter(oj_ol_flat) 145 | oj_flat = [ojp.get_known() if ojp.is_known() else next(oj_ol_flat_) 146 | for ojp in oj_pvals] 147 | ol_flat = [olp.get_known() if olp.is_known() else next(oj_ol_flat_) 148 | for olp in ol_pvals] 149 | assert next(oj_ol_flat_, None) is None 150 | return (tree_unflatten(f_out_tree, oj_flat), 151 | tree_unflatten(f_out_tree, ol_flat)) 152 | # make partial eval a pytree 153 | return primals_out, Partial(lap_pe, consts) 154 | 155 | 156 | def get_jsize(jacobians): 157 | try: 158 | jsize, = set(map(lambda x:x.shape[0], tree_flatten(jacobians)[0])) 159 | return jsize 160 | except ValueError: 161 | msg = "jacobians have inconsistent first dimensions for different arguments" 162 | raise ValueError(msg) from None 163 | 164 | 165 | def check_no_nested(primals, jacobians, laplacians): 166 | for i, (x, j, l) in enumerate(zip(primals, jacobians, laplacians)): 167 | for t, name in ((x, "primal"), (j, "jacobian"), (l, "laplacian")): 168 | treedef = tree_structure(t) 169 | if not treedef_is_leaf(treedef): 170 | raise ValueError(f"{name} value at position {i} is not an array") 171 | 172 | 173 | @lu.transformation2 174 | def lap_fun(f, jsize, instantiate, primals, jacobians, laplacians): 175 | tag = core.TraceTag() 176 | jacobians = [zero_tangent_from_primal(j, jsize) if type(j) is not Zero 177 | and lax.dtype(j) == float0 else j for j in jacobians] 178 | laplacians = [zero_tangent_from_primal(l, jsize) if type(l) is not Zero 179 | and lax.dtype(l) == float0 else l for l in laplacians] 180 | out_primals, out_jacs, out_laps = f(tag, jsize, primals, jacobians, laplacians) 181 | if type(instantiate) is bool: 182 | instantiate = [instantiate] * len(out_jacs) 183 | out_jacs = [instantiate_zeros(j) if inst else j 184 | for j, inst in zip(out_jacs, instantiate)] 185 | out_laps = [instantiate_zeros(l) if inst else l 186 | for l, inst in zip(out_laps, instantiate)] 187 | return out_primals, out_jacs, out_laps 188 | 189 | 190 | @lu.transformation2 191 | def lap_subtrace(f, tag, jsize, primals, jacobians, laplacians): 192 | with core.take_current_trace() as parent_trace: 193 | trace = LapTrace(tag, parent_trace, jsize) 194 | in_tracers = smap(partial(maybe_lap_tracer, trace), 195 | primals, jacobians, laplacians) 196 | with core.set_current_trace(trace): 197 | ans = f(*in_tracers) 198 | out_primals, out_jacs, out_laps = unzip3(smap(trace.to_pjl_tuple, ans)) 199 | return out_primals, out_jacs, out_laps 200 | 201 | 202 | def maybe_lap_tracer(trace, primal, jacobian, laplacian): 203 | if ((type(jacobian) is Zero or lax.dtype(jacobian) == float0) 204 | and (type(laplacian) is Zero or lax.dtype(laplacian) == float0)): 205 | return primal 206 | else: 207 | return LapTracer(trace, primal, jacobian, laplacian) 208 | 209 | 210 | class LapTracer(core.Tracer): 211 | __slots__ = ["primal", "jacobian", "laplacian"] 212 | 213 | def __init__(self, trace, primal, jacobian, laplacian): 214 | self._trace = trace 215 | self.primal = primal 216 | self.jacobian = jacobian 217 | self.laplacian = laplacian 218 | 219 | @property 220 | def aval(self): 221 | return core.get_aval(self.primal) 222 | 223 | def full_lower(self): 224 | if type(self.jacobian) is Zero and type(self.laplacian) is Zero: 225 | return core.full_lower(self.primal) 226 | else: 227 | return self 228 | 229 | 230 | class LapTrace(core.Trace): 231 | 232 | def __init__(self, tag, parent_trace, jsize): 233 | super().__init__() 234 | self.tag = tag 235 | self.parent_trace = parent_trace 236 | self.jsize = jsize 237 | 238 | def to_pjl_tuple(self, val): 239 | if isinstance(val, LapTracer) and val._trace.tag is self.tag: 240 | return val.primal, val.jacobian, val.laplacian 241 | else: 242 | return (val, 243 | zero_tangent_from_primal(val, self.jsize), 244 | zero_tangent_from_primal(val)) 245 | 246 | def process_primitive(self, primitive, tracers, params): 247 | jsize = self.jsize 248 | primals_in, jacs_in, laps_in = unzip3(smap(self.to_pjl_tuple, tracers)) 249 | with core.set_current_trace(self.parent_trace): 250 | if primitive in lap_rules: 251 | rule = lap_rules[primitive] 252 | primal_out, jac_out, lap_out = rule( 253 | jsize, primals_in, jacs_in, laps_in, **params) 254 | else: 255 | primal_out, jac_out, lap_out = primitive_by_jvp( 256 | primitive, jsize, primals_in, jacs_in, laps_in, **params) 257 | if not primitive.multiple_results: 258 | return maybe_lap_tracer(self, primal_out, jac_out, lap_out) 259 | else: 260 | return [maybe_lap_tracer(self, p, j, l) 261 | for p, j, l in zip(primal_out, jac_out, lap_out)] 262 | 263 | def process_custom_jvp_call(self, prim, fun, jvp, tracers, *, 264 | symbolic_zeros): 265 | primals_in, jacs_in, laps_in = unzip3(smap(self.to_pjl_tuple, tracers)) 266 | if all(type(t.jacobian) is type(t.laplacian) is Zero for t in tracers): 267 | return prim.bind_with_trace(self.parent_trace, (fun, jvp, *primals_in), 268 | dict(symbolic_zeros=symbolic_zeros)) 269 | if symbolic_zeros: 270 | raise NotImplementedError("symbolic_zeros not implemented") 271 | with core.set_current_trace(self.parent_trace): 272 | jacs_in = smap(ad.instantiate_zeros, jacs_in) 273 | laps_in = smap(ad.instantiate_zeros, laps_in) 274 | in_avals = smap(shaped_abstractify, (*primals_in, *laps_in)) 275 | jaxpr, _, consts, *_ = pe.trace_to_jaxpr_dynamic(jvp, in_avals) 276 | def _jvp(p_in, t_in): 277 | outs = core.eval_jaxpr(jaxpr, consts, *p_in, *t_in) 278 | p_out, t_out = split_list(outs, [len(outs) // 2]) 279 | return p_out, t_out 280 | primals_out, jacs_out, laps_out = vhv_by_jvp( 281 | _jvp, self.jsize, primals_in, jacs_in, laps_in) 282 | return [maybe_lap_tracer(self, p, j, l) 283 | for p, j, l in zip(primals_out, jacs_out, laps_out)] 284 | 285 | def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers, out_trees): 286 | raise TypeError("can't apply forward-mode laplacian to a custom_vjp " 287 | "function.") 288 | 289 | 290 | call_param_updaters: dict[ext_core.Primitive, Callable[..., Any]] = {} 291 | 292 | 293 | def zero_tangent_from_primal(primal, jsize=None): 294 | zero = Zero.from_primal_value(primal) 295 | if jsize is None: 296 | return zero 297 | aval = zero.aval 298 | return Zero(aval.update(shape=(jsize, *aval.shape))) 299 | 300 | 301 | @lu.transformation_with_aux2 302 | def flatten_fun_output(f, store, *args): 303 | ans = f(*args) 304 | ans, tree = tree_flatten(ans) 305 | store.store(tree) 306 | return ans 307 | 308 | 309 | def my_jvp(fun, primals, tangents): 310 | # this jvp is transparant to Zero, and assumes flattened input 311 | f, out_tree = flatten_fun_output( 312 | lu.wrap_init(fun, debug_info=debug_info("lap_innerjvp", fun, primals, {}))) 313 | jvp_f = ad.jvp(f, instantiate=False) 314 | out_primals, out_tangents = jvp_f.call_wrapped(primals, tangents) 315 | out_tree = out_tree() 316 | return (tree_unflatten(out_tree, out_primals), 317 | tree_unflatten(out_tree, out_tangents)) 318 | 319 | 320 | def vhv_by_jvp(f_jvp, jsize, primals_in, jacs_in, laps_in): 321 | z0, z1, z2 = primals_in, jacs_in, laps_in 322 | def vhv(v): 323 | inner = lambda *a: f_jvp(a, v)[1] 324 | return my_jvp(inner, z0, v) 325 | # second term in laplacian 326 | o0, o2_2 = f_jvp(z0, z2) 327 | multi_out = not treedef_is_leaf(tree_structure(o0)) 328 | # jacobian and first term in laplacian, handle all empty case 329 | if all(type(j) is Zero for j in z1): 330 | zero_o1_fn = partial(zero_tangent_from_primal, jsize=jsize) 331 | o1 = jax.tree_util.tree_map(zero_o1_fn, o0) 332 | return o0, o1, o2_2 333 | o1, o2_1 = jax.vmap(vhv, in_axes=0, out_axes=0)(z1) 334 | _sum0 = lambda x: x.sum(0) if type(x) is not Zero else x 335 | _add_o2 = lambda a, b: ad.add_tangents(_sum0(a), b) 336 | o2 = smap(_add_o2, o2_1, o2_2) if multi_out else _add_o2(o2_1, o2_2) 337 | return o0, o1, o2 338 | 339 | 340 | def primitive_by_jvp(primitive, jsize, primals_in, jacs_in, laps_in, **params): 341 | func = partial(primitive.bind, **params) 342 | f_jvp = partial(my_jvp, func) 343 | return vhv_by_jvp(f_jvp, jsize, primals_in, jacs_in, laps_in) 344 | 345 | 346 | ### rule definitions 347 | 348 | lap_rules: dict[ext_core.Primitive, Callable[..., Any]] = {} 349 | 350 | 351 | def defmultivar(prim): 352 | lap_rules[prim] = partial(multivar_prop, prim) 353 | 354 | def multivar_prop(prim, jsize, primals_in, jacs_in, laps_in, **params): 355 | pprim = partial(prim.bind, **params) 356 | z0, z1, z2 = primals_in, jacs_in, laps_in 357 | o0, o2_2 = my_jvp(pprim, z0, z2) 358 | if all(type(j) is Zero for j in jacs_in): 359 | o1 = zero_tangent_from_primal(o0, jsize) 360 | return o0, o1, o2_2 361 | o1 = jax.vmap(lambda v: my_jvp(pprim, z0, v)[1], 0, 0)(z1) 362 | _mul2 = lambda x: 2*x if type(x) is not Zero else x 363 | _sum0 = lambda x: x.sum(0) if type(x) is not Zero else x 364 | def vhv(v1, v2): 365 | inner = lambda *a: my_jvp(pprim, a, v1)[1] 366 | return my_jvp(inner, z0, v2)[1] 367 | def vmapped_vhv(v1, v2): 368 | if not tree_flatten((v1, v2))[0]: # empty tree 369 | return zero_tangent_from_primal(o0) 370 | return jax.vmap(vhv, in_axes=0, out_axes=0)(v1, v2) 371 | o2 = o2_2 372 | for i in range(len(primals_in)): 373 | triu_z1 = [zero_tangent_from_primal(p, jsize) if j <= i else t 374 | for j, (p, t) in enumerate(zip(z0,z1))] 375 | diag_z1 = [zero_tangent_from_primal(p, jsize) if j != i else t 376 | for j, (p, t) in enumerate(zip(z0,z1))] 377 | o2_1_diag = vmapped_vhv(diag_z1, diag_z1) 378 | o2 = ad.add_tangents(_sum0(o2_1_diag), o2) 379 | o2_1_triu = vmapped_vhv(triu_z1, diag_z1) 380 | o2 = ad.add_tangents(_mul2(_sum0(o2_1_triu)), o2) 381 | return o0, o1, o2 382 | 383 | defmultivar(lax.mul_p) 384 | defmultivar(lax.dot_general_p) 385 | defmultivar(lax.conv_general_dilated_p) 386 | # This rule will only be faster when the operator is bilinear. 387 | # Because the diagonal part of o2_1 is Zero. 388 | # Hence we do not apply it for the following primitives. 389 | # defmultivar(lax.div_p) 390 | # defmultivar(lax.rem_p) 391 | # defmultivar(lax.pow_p) 392 | # defmultivar(lax.atan2_p) 393 | 394 | 395 | def lap_jaxpr(jaxpr, jsize, nonzeros1, nonzeros2, instantiate): 396 | if type(instantiate) is bool: 397 | instantiate = (instantiate,) * len(jaxpr.out_avals) 398 | return _lap_jaxpr(jaxpr, jsize, 399 | tuple(nonzeros1), tuple(nonzeros2), tuple(instantiate)) 400 | 401 | @weakref_lru_cache 402 | def _lap_jaxpr(jaxpr, jsize, nonzeros1, nonzeros2, instantiate): 403 | assert len(jaxpr.in_avals) == len(nonzeros1) == len(nonzeros2) 404 | f = lu.wrap_init(ext_core.jaxpr_as_fun(jaxpr), debug_info=jaxpr.jaxpr.debug_info) 405 | f_jvp, out_nonzeros = f_lap_traceable(lap_fun(lap_subtrace(f), jsize, instantiate), 406 | jsize, nonzeros1, nonzeros2) 407 | jac_avals = [aval.update(shape=(jsize, *aval.shape)) 408 | for aval, nz in zip(jaxpr.in_avals, nonzeros1) if nz] 409 | lap_avals = [aval for aval, nz in zip(jaxpr.in_avals, nonzeros2) if nz] 410 | avals_in = [*jaxpr.in_avals, *jac_avals, *lap_avals] 411 | jaxpr_out, avals_out, literals_out = pe.trace_to_jaxpr_dynamic(f_jvp, avals_in) 412 | return ext_core.ClosedJaxpr(jaxpr_out, literals_out), out_nonzeros() 413 | 414 | @lu.transformation_with_aux2 415 | def f_lap_traceable(f, store, jsize, nonzeros1, nonzeros2, *primals_nzjacs_nzlaps): 416 | assert len(nonzeros1) == len(nonzeros2) 417 | num_primals = len(nonzeros1) 418 | primals = list(primals_nzjacs_nzlaps[:num_primals]) 419 | nzjacs_nzlaps = iter(primals_nzjacs_nzlaps[num_primals:]) 420 | jacs = [next(nzjacs_nzlaps) if nz else zero_tangent_from_primal(p, jsize) 421 | for p, nz in zip(primals, nonzeros1)] 422 | laps = [next(nzjacs_nzlaps) if nz else zero_tangent_from_primal(p) 423 | for p, nz in zip(primals, nonzeros2)] 424 | primals_out, jacs_out, laps_out = f(primals, jacs, laps) 425 | out_nonzeros1 = [type(t) is not Zero for t in jacs_out] 426 | out_nonzeros2 = [type(t) is not Zero for t in laps_out] 427 | nonzero_jacs_out = [t for t in jacs_out if type(t) is not Zero] 428 | nonzero_laps_out = [t for t in laps_out if type(t) is not Zero] 429 | store.store((out_nonzeros1, out_nonzeros2)) 430 | return list(primals_out) + nonzero_jacs_out + nonzero_laps_out 431 | 432 | 433 | def _pjit_lap_rule(jsize, primals_in, jacs_in, laps_in, *, jaxpr, **params): 434 | is_nz_jacs_in = [type(t) is not Zero for t in jacs_in] 435 | is_nz_laps_in = [type(t) is not Zero for t in laps_in] 436 | jaxpr_lap, (is_nz_jacs_out, is_nz_laps_out) = lap_jaxpr( 437 | jaxpr, jsize, is_nz_jacs_in, is_nz_laps_in, instantiate=False) 438 | 439 | def _filter_zeros(is_nz_l, l): 440 | return (x for nz, x in zip(is_nz_l, l) if nz) 441 | _fz_jacs_in = partial(_filter_zeros, is_nz_jacs_in) 442 | _fz_laps_in = partial(_filter_zeros, is_nz_laps_in) 443 | _fz_jacs_out = partial(_filter_zeros, is_nz_jacs_out) 444 | _fz_laps_out = partial(_filter_zeros, is_nz_laps_out) 445 | 446 | insd, outsd = params["in_shardings"], params["out_shardings"] 447 | dovar = params["donated_invars"] 448 | new_params = { 449 | **params, 450 | "jaxpr": jaxpr_lap, 451 | "in_shardings": (*insd, *_fz_jacs_in(insd), *_fz_laps_in(insd)), 452 | "out_shardings": (*outsd, *_fz_jacs_out(outsd), *_fz_laps_out(outsd)), 453 | "donated_invars": (*dovar, *_fz_jacs_in(dovar), *_fz_laps_in(dovar)), 454 | } 455 | if "in_layouts" in params: 456 | inlo, outlo = params["in_layouts"], params["out_layouts"] 457 | new_params["in_layouts"] = (*inlo, *_fz_jacs_in(inlo), *_fz_laps_in(inlo)) 458 | new_params["out_layouts"] = (*outlo, *_fz_jacs_out(outlo), *_fz_laps_out(outlo)) 459 | 460 | outputs = jit_p.bind( 461 | *primals_in, 462 | *_fz_jacs_in(jacs_in), 463 | *_fz_laps_in(laps_in), 464 | **new_params 465 | ) 466 | 467 | primals_out, nzjacs_nzlaps = split_list(outputs, [len(jaxpr.jaxpr.outvars)]) 468 | assert len(primals_out) == len(jaxpr.jaxpr.outvars) 469 | nzjacs_nzlaps_it = iter(nzjacs_nzlaps) 470 | jacs_out = [next(nzjacs_nzlaps_it) if nz else Zero(aval) 471 | for nz, aval in zip(is_nz_jacs_out, jaxpr.out_avals)] 472 | laps_out = [next(nzjacs_nzlaps_it) if nz else Zero(aval) 473 | for nz, aval in zip(is_nz_laps_out, jaxpr.out_avals)] 474 | return primals_out, jacs_out, laps_out 475 | 476 | lap_rules[jit_p] = _pjit_lap_rule 477 | --------------------------------------------------------------------------------