File size: 2,290 Bytes
a4ba047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Patch scikit-learn 1.9.1 GaussianProcessRegressor.log_marginal_likelihood (venv only).

The multi-target gradient builds inner_term = einsum("ik,jk->ijk", alpha, alpha),
an (n, n, n_targets) array: 89 x 89 x 161679 float64 = 10.25 GB for the GP run,
which the 10G scope killed. The gradient sums that array over targets at the end,
so the same quantity is

    sum_l inner_term[..., l] = alpha @ alpha.T - n_targets * K_inv

and the gradient is 0.5 * einsum("ij,jik->k", that, K_gradient): O(n^2) memory.
Only the floating-point summation order changes.

Usage: python -I patch_sklearn_gpr.py VENV_SITE_PACKAGES ORIG_COPY
"""

import shutil
import sys
from pathlib import Path

OLD = """            inner_term = np.einsum("ik,jk->ijk", alpha, alpha)
            # compute K^-1 of shape (n_samples, n_samples)
            K_inv = cho_solve(
                (L, GPR_CHOLESKY_LOWER), np.eye(K.shape[0]), check_finite=False
            )
            # create a new axis to use broadcasting between inner_term and
            # K_inv
            inner_term -= K_inv[..., np.newaxis]
"""
NEW = """            # dwi-hmc M0 patch: sum over outputs first (O(n^2) memory).
            K_inv = cho_solve(
                (L, GPR_CHOLESKY_LOWER), np.eye(K.shape[0]), check_finite=False
            )
            inner_sum = alpha @ alpha.T - alpha.shape[1] * K_inv
"""
OLD2 = """            log_likelihood_gradient_dims = 0.5 * np.einsum(
                "ijl,jik->kl", inner_term, K_gradient
            )
            # the log likelihood gradient is the sum-up across the outputs
            log_likelihood_gradient = log_likelihood_gradient_dims.sum(axis=-1)
"""
NEW2 = """            log_likelihood_gradient = 0.5 * np.einsum("ij,jik->k", inner_sum, K_gradient)
"""


def main(site: Path, orig: Path) -> None:
    path = site / "sklearn" / "gaussian_process" / "_gpr.py"
    text = path.read_text()
    if "dwi-hmc M0 patch" in text:
        print("already patched")
        return
    assert text.count(OLD) == 1 and text.count(OLD2) == 1, "unexpected sklearn source"
    shutil.copyfile(path, orig)
    path.write_text(text.replace(OLD, NEW).replace(OLD2, NEW2))
    print(f"patched {path}; original kept at {orig}")


if __name__ == "__main__":
    main(Path(sys.argv[1]), Path(sys.argv[2]))